malloc()/ free()在一个循环中

时间:2014-10-25 16:06:52

标签: c malloc free

我有一个类的作业,我有一个文本文件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()函数将分配越来越多的内存,而这些内存不会被释放。 但是,如果我取消注释free(bikeIdText);中的bikeIdText = NULL;main()行,则输出会显示使用相同的内存位置,因为较长的值不会被较短的值覆盖。 这种情况下的输出:

"16415""65415""55415"

我怎么能解决这个问题?

2 个答案:

答案 0 :(得分:1)

字符串的最后一个字符未设置为&#39; \ 0&#39;因此,&#34;%s&#34;打印得比它应该多(%s在\ 0字节处停止输出)。

在返回之前尝试malloc一个字节char* attrText = malloc(lineLength - attrLength + 2)并设置attrText[lineLength - attrLength + 1] = '\0'

答案 1 :(得分:1)

  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' ;

这假定line一个附加字符结尾。