Monday 15 March 2010

c - malloc()/free() in a loop -



c - malloc()/free() in a loop -

i have assignment class have text file, bikes.txt. contents attributes of bikes so:

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

right i'm trying read bike_id's, , have question:

#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 "=" , newline memcpy(attrtext, line + attrlength + 1, linelength - (attrlength + 2)); homecoming attrtext; }

the above code works. output is:

"16415""6541""5"

the problem - if i'm right - getattribute() function allocate more , more memory won't freed. however, if uncomment free(bikeidtext); , bikeidtext = null; lines in main(), output shows same memory location used, because longer values won't overwritten shorter ones. output in case:

"16415""65415""55415"

how solve problem?

this

char* attrtext = malloc(linelength - attrlength + 1);

shall be

char * attrtext = malloc(linelength - (attrlength + 1)); attrtext[linelength - (attrlength + 1) - 1] = '\0' ;

or equivalent

char * attrtext = malloc(linelength - attrlength - 1); attrtext[linelength - attrlength - 2] = '\0' ;

this assumes line end one addtional character.

c malloc free

No comments:

Post a Comment