【问题标题】:memory overwrite when reading strings in c在c中读取字符串时内存覆盖
【发布时间】:2017-01-24 17:53:49
【问题描述】:

我正在处理的代码需要一个双精度向量作为输入,我试图通过使用我在 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 个输入和“停止”),我得到了

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 */

【问题讨论】:

  • 您是否尝试过使用调试器逐行执行代码?

标签: c string memory input overwrite


【解决方案1】:

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

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

vector_add(&v, strdup(c));

【讨论】:

    猜你喜欢
    • 2021-09-13
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    相关资源
    最近更新 更多