在c中读取字符串时内存覆盖

memory overwrite when reading strings in c

我正在处理的代码需要一个双精度向量作为输入,我试图通过使用在 git 上找到的 this small library 使其大小可变。使用字符串而不是双精度数的第一次迭代是:

printf("Write vector components (type 'stop' to stop): \n");
int stop = 0;
while (!stop)
{
    fgets(c, sizeof(c), stdin);
    if (strcmp("stop\n",c)!=0)
    {
        vector_add(&v, c);
    } else {
        stop = 1;
    }
}

但是,当我打印结果时(例如使用 3 个输入和 "stop"),我得到

the vector is: stop stop stop

每次我输入一个新的组件时,我都尝试写第一个组件,结果是最后一个覆盖第一个(并且推而广之,给定最终结果,每个组件)。

但是,如果我手动使用 vector_add,则不会发生这种情况。例如,我尝试将 git 中的示例与我自己的代码结合起来,完整的输出是:

emil hannes lydia olle erik stop stop stop stop

所以它只在读取时覆盖。我什至无法开始理解正在发生的事情。已经 2 年没有写任何 C 语言了,我要重新开始。

完整代码(不包括矢量库):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "vector.c"

void main(int argc, char* argv[]) {
    char        c[20];
    vector      v; vector_init(&v);


    printf("Write vector components (type 'stop' to stop):\n");
    int stop = 0;
    while (!stop)
    {
        fgets(c, sizeof(c), stdin);
        if (strcmp("stop\n",c)!=0)
        {
            vector_add(&v, c);
            // printf("%s\n", (char*)vector_get(&v, 0));
        } else {
            stop = 1;
        }
    }


    printf("The vector is:\n");
    for (int i = 0; i < vector_count(&v); i++) {
        printf("%s\n", (char*)vector_get(&v, i));
    }

} /* main */

vector_add 不会复制数据,因此您的字符串仍存储在变量 c 中。当您读取新字符串时,它会覆盖旧字符串。

如果你的字符串库包含strdup,你可以试试这个:

vector_add(&v, strdup(c));