【问题标题】:Why is strcpy appending junk characters to the end of a small fraction of strings?为什么 strcpy 将垃圾字符附加到一小部分字符串的末尾?
【发布时间】: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 的错,但我想不出错误还会出现在哪里。

【问题讨论】:

  • 除了在 r​​emove_extra 中使用不安全的字符串外,您还应该使用更安全的 fscanf 形式,带有 %as(和字符串指针地址)或 %199s。
  • 只是为了我自己的启迪,remove_extra中的字符串使用有什么不安全的地方?
  • 好吧,它不是remove_extra,它是调用者。如果在此之前没有终止 \0,它将在分配的参数的 200 个字节后面搜索。

标签: c string strcpy


【解决方案1】:

如果您将len 计算为src 的长度,那么对strncpy 的幼稚使用——尽管它可能很诱人——是不正确的:

 size_t len = strlen(src);
 dest = malloc(len);       /* DON'T DO THIS */
 strncpy(dest, src, len);  /* DON'T DO THIS, EITHER */

strncpy 精确复制 len 字节;它确实不保证在末尾放置一个 NUL 字节。由于len正好是src的长度,所以src的第一个len字节内没有NUL字节,NUL字节也不会被strncpy插入。

如果您改用strcpy(所谓的“不安全”界面):

strcpy(dest, src);

应该没问题,只是dest 不够大。你真正需要做的是:

dest = malloc(strlen(src) + 1);  /* Note: include space for the NUL */
strcpy(dest, src);

或者,如果你有有用的strdup 函数:

dest = strdup(src);

【讨论】:

  • 这就像一个魅力。在这里,我认为在 remove_extra 中添加 NUL 字节是安全的。我想是新手狂妄自大。无论如何,非常感谢您的回复。
【解决方案2】:

您很可能忘记在字符串末尾复制空终止符,请记住 strlen(str) 给出了可见字符的数量,您还需要在末尾添加 '\0'。 你需要做的

temp->hyperlink =(char *)malloc(strlen(new_link)+1);//char is one byte, sizeof(char)=1

和 strcpy(temp->hyperlink, new_link); 应该可以正常工作。

为什么不使用strdup?

【讨论】:

  • strdup 是非标准的。 (这不是必然不使用它的理由。)
猜你喜欢
  • 1970-01-01
  • 2010-09-21
  • 2021-11-13
  • 2014-03-06
  • 2022-12-11
  • 2017-09-29
  • 1970-01-01
  • 2020-08-19
  • 2016-03-14
相关资源
最近更新 更多