我有一个类(class)作业,其中有一个文本文件 bikes.txt
。内容是自行车的属性,如下所示:
bike_id=16415
bike_station_id=455
bike_status=free
bike_id=6541
bike_station_id=1
bike_status=reserved
bike_id=5
bike_station_id=6451
bike_status=reserved
现在我正在尝试读取所有 bike_id
,我有一个问题:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* getAttribute(const char* attr, const char* line);
int main(int argc, char** argv)
{
FILE* file = fopen("bikes.txt", "r");
if (file != NULL)
{
char line[256];
while (fgets(line, sizeof(line), file))
{
if (strstr(line, "bike_id=") != NULL)
{
char* bikeIdText = getAttribute("bike_id", line);
printf("\"%s\"", bikeIdText);
//free(bikeIdText);
//bikeIdText = NULL;
}
}
}
}
char* getAttribute(const char* attr, const char* line)
{
int lineLength = strlen(line);
int attrLength = strlen(attr);
// +1 because of "="
char* attrText = malloc(lineLength - attrLength + 1);
// +2 because of "=" and NEWLINE
memcpy(attrText, line + attrLength + 1, lineLength - (attrLength + 2));
return attrText;
}
上面的代码有效。输出是:
"16415""6541""5"
问题是 - 如果我是对的 - getAttribute()
函数将分配越来越多的内存,这些内存不会被释放。
但是,如果我在 main()
中取消注释 free(bikeIdText);
和 bikeIdText = NULL;
行,输出显示相同的内存使用位置,因为较长的值不会被较短的值覆盖。
这种情况下的输出:
"16415""65415""55415"
我该如何解决这个问题?
最佳答案
这个
char* attrText = malloc(lineLength - attrLength + 1);
应该是
char * attrText = malloc(lineLength - (attrLength + 1));
attrText[lineLength - (attrLength + 1) - 1] = '\0' ;
或等价物
char * attrText = malloc(lineLength - attrLength - 1);
attrText[lineLength - attrLength - 2] = '\0' ;
这假定行
以一个附加字符结束。
关于c - 循环中的 malloc()/free(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26564438/