gpt4 book ai didi

c - Fork数组赋值冲突

转载 作者:行者123 更新时间:2023-11-30 18:33:20 25 4
gpt4 key购买 nike

我有以下内容并尝试从文件中逐行读取,然后将该行放入数组中。

char **history = malloc(sizeof(char*) * 1000);
int history_size = 0;

fp = fopen(file, "r");
if (fp == NULL)
exit(EXIT_FAILURE);

while ((read = getline(&line, &len, fp)) != -1) {
if(strstr(line, "\n") != NULL) {
line[strlen(line) - 1] = '\0';
}

if (strcmp(line, "History") == 0) {
for(int m = 0; m < history_size; m++) {
printf("%s\n", history[m]);
}
} else {
//printf("....%s\n", line);
history[history_size++] = line;
}
}

fclose(fp);
if (line)
free(line);

问题是数组不收集行,当我运行代码时,它会打印与文件中的行一样多的“历史记录”。我好几天都无法忍受。历史记录应保留历史记录行之前发生的行。

最佳答案

它与fork()无关。

来自manpage getline:

If *lineptr is NULL, then getline() will allocate a buffer for storing the line, which should be freed by the user program. (In this case, the value in *n is ignored.)

If the buffer is not large enough to hold the line, getline() resizes it with realloc(3), updating *lineptr and *n as necessary.

问题在于您正在将地址分配给数组元素。最后它们都指向同一个地址(取决于getlinerealloc)。由于您没有 malloc,因此 getline 必须在内部完成此操作,并且在后续调用中 reallocgetline 内部使用code> 通常会保留相同的地址。因此,在循环中,当您的 line 更新时,所有数组元素也可能会更新,因为大多数数组元素都指向相同的地址。

因此,最后当您达到 line"History" 的条件时,它们只是显示 line 包含的内容(即“History”) )因为它们都指向与 line 相同的地址。

这是问题的主要原因,但是 fork() 肯定会让您偏离您想要的输出方式。尽管 fork() 只会干扰您的输出,并且可以通过在 fork() 返回 0 时不打印来轻松处理。

更正:

1)正如您在问题评论中所说,如果fork() == 0,您正在执行execvp(),它不应该引起问题。您需要做的就是:

history[history_size] = malloc(sizeof(char)* (strlen(line)+1));
strcpy(history[history_size++], line);

而不是直接赋值。

2) 请记住在每次迭代时free()释放由line中的getline()分配的内存。

关于c - Fork数组赋值冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58121932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com