在什么情况下(如果有的话) strcat() 会挂起?

Under what circumstances (if ever) does strcat() hang?

我在 C:

的一个函数中有这段代码
char* root = "/home/OS/homework/user/honorsupgrade/HTML";
requestInfo->resource = "/bing"
printf("1\n");
int counter = 0;
for(counter = 0; counter < 100; counter++)
{
    if(root[counter] == '[=10=]')
    {
        printf("True1\n");
        break;
    }
}
for(counter = 0; counter < 100; counter++)
{
    if(requestInfo->resource[counter] == '[=10=]')
    {
        printf("True2\n");
        break;
    }
}
printf("2\n");
fflush(stdout);
strcat(root, requestInfo->resource);
printf("3\n");
fflush(stdout);
return open(root, 0_RDONLY);

...

根据需要索取信息

struct ReqInfo
{
    char *resource;
}

我在 C 中创建了两个字符串(字符指针),但由于某些原因,当我将这些方法传递给 strcat() 时,strcat() 从未 returns。这会导致程序挂起。我已经测试以确保两个字符串都具有空终止符(因此 strcat 不会尝试连接超过它应该的)。该程序将打印 1 和 2,但从不打印 3,这意味着它永远不会通过 strcat() 调用,因为我正在刷新缓冲区以确保那里没有问题。 \

编辑:我在这个代码块之外创建了结构,当用 char* 资源替换 "requestInfo->resource" 并使其成为“/bing”时,我遇到了同样的问题

调用未定义的行为原则上可能导致任何事情,包括挂起您的程序。当您将指向字符串文字的指针作为 strcat.

的目标传递时,您会调用未定义的行为
// root points to a string literal. This is immutable!
char* root = "/home/OS/homework/user/honorsupgrade/HTML";

....

// Oops! Writing to *root is undefined behaviour!
strcat(root, requestInfo->resource);

您正在尝试修改 常量 字符串。语句

char* root = "/home/OS/homework/user/honorsupgrade/HTML";

设置 root 指针指向包含您的路径的 constant 字符串。不得修改 root 指向的内存,否则会调用 未定义的行为 。对 strcat() 的调用尝试修改超过常量字符串数据末尾的数据。听起来好像编译器放了一些重要的东西,而你覆盖了它。

正在尝试写入 const char *

尽管 char* root 是一个 char *,但它确实指向一个 const char *。写入是未定义的行为。

char* root = "/home/OS/homework/user/honorsupgrade/HTML";
....
strcat(root, requestInfo->resource);

代码应改为分配大小合适的工作缓冲区。

char buffer[1000];
strcpy(buffer, root);
strcat(buffer, requestInfo->resource);

在 C 中,程序员控制并负责内存分配。

您提供的代码将有未定义的行为,因为您要求 "strcat"(参见 "man strcat")将某些内容复制到一个未保留的位置(内存占用的末尾'root').

指向的字符串

很难说出你真正想做什么,但为了避免崩溃,你应该:

char[<static_buffer_lenght>] root = ...
...
strncat(root, <something>, sizeof(root) - strlen(root) - 1)

这将使您的程序稍微大一些,或者:

char *root = (char *)malloc(<size_of_dynamic_buffer>)
bzero((void *)root, <size_of_dynamic_buffer>)
if (!root) { <handle memory error here> }
...
strncat(root, <something>, <size_of_dynamic_buffer> - strlen(root) - 1)

这会让你的程序稍微变慢

有一段时间没有使用 'C',所以一些细节可能会导致编译警告('<','>' 中的任何内容你必须替换为正确的文本 - 当然)。