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

标签 c string memory input overwrite

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

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 个输入和“停止”),我得到了

vector 是: 停止 停止 停止

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

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

埃米尔 哈内斯 莉迪亚 奥莱 埃里克 停止 停止 停止 停止

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

完整代码(不包括 vector 库):

#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));

关于c - 在c中读取字符串时内存覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41835723/

相关文章:

regex - 从句子中提取数字

java - 两个 Java 字符串在不相等时表示它们相等

java - 使用compareTo和instanceOf比较字符串和整数

c++指针的内存分配 vector

c - 当给变量赋值以及从标准输入扫描它时,内部会发生什么?

c - OpenGL 3.3 不会绘制我的三角形

c - 有错误显示为 "comparison between pointer and integer (' int' 和 'const char *' )"

c - C 指针(总是)以有效地址内存开头吗?

PHP读取和解析大文件?

c - 我需要一个 ANSI C 格式的实时时钟,其精度可达毫秒?