gpt4 book ai didi

c - 从文件读取时出现 Malloc 错误

转载 作者:行者123 更新时间:2023-11-30 19:09:27 25 4
gpt4 key购买 nike

我有一个文件,其中每行字符串都采用这种格式

key1 = value1
key2 = value2
....

我需要提取第三列中的字符串。到目前为止我编写的代码是

    fp = fopen(file, "r");
assert(fp && "checkpoint file not found \n");

char **data = (char **) malloc(sizeof (char*) * lines ); // lines=100
size_t i = 0;

while ((read = getline(&line, &len, fp)) != -1){
size_t l = strlen(line);

char value[256];
sscanf( line, "%s %s %s", field, tmp, value); // field stores 'key1', tmp stores '+', value stores 'value1'

data[i] = value;
i++;
printf("%s \n", value);
// printf("%s %s\n", value, data[i]); -- when this line is uncommented, it leads to a seg-fault.
}
fclose(fp);


for (int i=0; i < lines; ++i)
free(data[i]);
free(data);

我收到错误“对象的 malloc 错误...,正在释放的指针未分配”。

最佳答案

我所看到的问题是,之前

  printf("%s %s\n", value, data[i]);

这一行,你正在做 i++这会改变 i 的值。然后data[i]指向未初始化的内存。将其作为参数传递给 %s原因undefined behavior .

[编辑:]

话又说回来,你正在做

 free(data[i]);

而,data[i]不是内存分配器函数返回的指针。这是 UB 的另一个原因。

也就是说,

关于c - 从文件读取时出现 Malloc 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43241594/

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