C: Realloc 的行为方式我不明白为什么

标签 c pointers malloc realloc

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]){

    char buffer[103];
    char **words = malloc(1 * sizeof(*words));
    size_t counter = 0;
    size_t array_size = 2;


    for(int i = 0; i < 5; i++){
        if(!fgets(buffer, 103, stdin)){
            fputs("fgets failed", stderr);
        }
        words[counter] = buffer;
        char **more_words = realloc(words, array_size * sizeof(*more_words));
        words = more_words;
        array_size++;
        counter ++;
    }
    printf("********************************************************");


    for(int i = 0; i < 5; i++){
        printf("%s\n", words[i]);
    }


}

现在这是我正在处理的简化代码。 我知道我不会处理很多可能发生的错误。

要点是,当您执行此操作时,单词数组似乎有 5 个“最后”条目。

假设你给 fgets :

1
2
3
4
5

然后

words[0] = 5;
words[1] = 5;
words[2] = 5;
words[3] = 5;
words[4] = 5;

为什么不是:

words[0] = 1;
words[1] = 2;
words[2] = 3;
words[3] = 4;
words[4] = 5;

?

最佳答案

问题不在于realloc,而在于您分配给您分配的指针的内容:

words[counter] = buffer;

buffer 始终是同一个指针,因此您最终会读取到缓冲区中的最后一个字符串。

您需要malloc 并为每一行复制缓冲区:

words[counter] = malloc(strlen(buffer)+1);
strcpy(words[counter], buffer);

不用说,您应该是 NULL - 在将 realloc 返回的值赋回给 words 之前检查它。

关于C: Realloc 的行为方式我不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36952663/

相关文章:

c - 从 main() 访问单独文件中的静态函数

c++ - 使用 malloc 时从 `void*' 到 `char*' 的无效转换?

c++ - call没有匹配函数,为什么?

c - 当超出堆(裸机)时,malloc() 不会返回 null

c++ - calloc 比 malloc 好吗?

c - 选择C程序中的目录以在其中运行

c - gcc arm __asm inline 在参数中传递常量

函数的返回类型可以是结构体吗?

c - 为什么在库函数之前有一个序列点?

c - 需要一些帮助来理解 C 中的指针和内存