【发布时间】:2015-10-23 08:16:02
【问题描述】:
这是一个找到与父路径相对应的相对路径的现有代码。除了 SUSE 12 和 GCC 4.7 之外,它一直在平台上按预期工作。 我在 cmets 中提到了错误的输出之一。 我试图了解为什么会发生这种情况? 这段代码有什么问题? 子字符串和父字符串都以 NUL 字符结尾。我看到的唯一另一件事是源和目标是从同一内存位置传递的,换句话说,我们正在尝试更新同一内存位置的值。 这是真正的问题吗?
//child = /dev/shm/4/tmp/backup/datadir/performance_schema/events_stages_summary_by_account_by_event_name.frm
//parent = /dev/shm/4/tmp/backup
char* get_relative_path(char *child, const char *parent)
{
char* start= child;
static char dot[] = "." ;
....
....
/* Check if child = parent + "/" + .... */
if (strstr(child, parent) == child)
{
int parent_len= strlen(parent);
/* parent path may or may not have the "/" suffix. check for both. */
if (parent[parent_len-1] == FN_LIBCHAR ||
child[parent_len] == FN_LIBCHAR)
{
child+= parent_len;
while (*child && *child == FN_LIBCHAR)
child++;
if (*child == 0)
return dot;
}
}
// At this point the value of
// start = /dev/shm/4/tmp/backup/datadir/performance_schema/events_stages_summary_by_account_by_event_name.frm
// child = datadir/performance_schema/events_stages_summary_by_account_by_event_name.frm
if(start != child)
{
stpncpy(start, child, PATH_MAX);
}
// At this point expected value of start = datadir/performance_schema/events_stages_summary_by_account_by_event_name.frm
// But actual value of start = datadir/performance_schenamevents_stages_summary_by_account_by_event_name.frm
return start;
}
【问题讨论】:
-
stpncpy 的手册页说字符串可能不重叠。您可以通过使用一个向后开始的函数来解决它,因此不会从已写入的位置读取。我不知道这是否是真正快速查看的实际问题,但这是一个潜在问题。
-
Ok ... jite 和@mch 指出了同样的问题