【发布时间】:2015-05-28 08:50:35
【问题描述】:
我有一个函数将包含超链接的字符串作为其输入,并尝试输出相同的超链接,但如果它包含问号,则该字符及其后面的所有字符都将被清除。
首先,我打开一个文本文件并读入包含链接的行,并且只有这样的链接:
FILE * ifp = fopen(raw_links,"r");
char link_to_filter[200];
if(ifp == NULL)
{
printf("Could not open %s for writing\n", raw_links);
exit(0);
}
while(fscanf(ifp,"%s", link_to_filter) == 1)
{
add_link(a,link_to_filter, link_under_wget);
};
fclose(ifp);
add_link 所做的部分工作是在问号后去掉链接的不必要部分(如 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/online-giving/step1.php?new=1),这导致我对 wget 的调用出现问题。它通过这个函数 remove_extra 提供 link_to_filter 来做到这一点,如下所示。
char * remove_extra(char * url)
{
char * test = url;
int total_size;
test = strchr(url,'?');
if (test != NULL)
{
total_size = test-url;
url[total_size] = '\0';
}
return url;
}
在 remove_extra 结束时,在从 remove_extra 返回时以及在使用 strcpy 之前立即调用 printf,就像这样
printf("%s",url);
将打印出我希望看到的内容(例如 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/online-giving/step1.php,不带“?”或尾随字符),但在这段代码运行后立即
struct node * temp = (struct node *)malloc(sizeof(struct node));
char * new_link = remove_extra(url);
temp->hyperlink =(char *)malloc(strlen(new_link) * sizeof(char));
strncpy(temp->hyperlink, new_link, strlen(new_link));
成员超链接上的 printf 的结果偶尔会在末尾有一个垃圾字符(有时是“A”或“Q”或“!”,但总是相同的字符对应于相同的字符串)。如果每个链接或特定类型的链接都发生这种情况,我可以弄清楚, 但它可能仅适用于每 20 个链接,而且它恰好适用于短链接和长链接。
例如 xxxxxxxxxxxxxxxxxxxx/hr/ --> xxxxxxxxxxxxxxxxxxxx/hr/!
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/windows-to-the-past/ --> xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/windows-to-the-past/Q
strcpy 和自制的字符串复制循环都会发生这种情况,所以我倾向于认为这不是 strcpy 的错,但我想不出错误还会出现在哪里。
【问题讨论】:
-
除了在 remove_extra 中使用不安全的字符串外,您还应该使用更安全的 fscanf 形式,带有 %as(和字符串指针地址)或 %199s。
-
只是为了我自己的启迪,remove_extra中的字符串使用有什么不安全的地方?
-
好吧,它不是remove_extra,它是调用者。如果在此之前没有终止 \0,它将在分配的参数的 200 个字节后面搜索。