c - 循环中的 malloc()/free()

标签 c malloc free

我有一个类(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/

相关文章:

c - 使用 malloc 在 C 中正确使用/创建动态 cstrings?

无法将值输入分配的矩阵

c - 复制结构时出现段错误

c - 释放 C 结构体的字符串成员

C++ 释放静态变量

c++ - 具有-static 和-rdynamic 的backtrace_symbols()

c - 提高置换检验的 p 值矩阵构造的性能

c - 简单的 C 代码错误

c++ - 如何将我的项目转换为多线程应用程序

c - 如何在 C 中表示科学记数法