I have a program where I load data from a text file into an array of structs. My struct looks like this:
typedef struct A {
int id;
char* name;
char* desc;
} A;
I start loading the file from my main function:
int main(void) {
A* a;
int* length = 0;
arr = betolt("name.txt", &length);
...
free(arr);
return 0;
}
Then - in a different header file - the real logic happens like this:
A* load(char* file_name, int* length) {
FILE* fp = fopen(file_name, "r");
if (fp == NULL) return NULL;
size_t ar_length = 500;
size_t line_counter = 0;
char** lines = malloc(ar_length);
char line[256];
while (fgets(line, sizeof(line), fp)) {
lines[line_counter] = malloc(256);
strcpy(lines[line_counter], line);
line_counter++;
if(line_counter > sizeof(lines)){
ar_length *= 2;
lines = realloc(lines, ar_length);
}
}
*length = line_counter;
fclose(fp);
return process(lines, line_counter);
}
A* process(char** lines, int length) {
A* arr = (A*) malloc(length * sizeof(A));
for (int i = 0; i < length; ++i) {
char* line = lines[i];
char* ptr = strtok(line, ";");
A a;
a.id = i;
int j = 0;
while (ptr != NULL) {
if (j == 0) {
a.name = ptr;
} else if (j == 1) {
a.desc = ptr;
}
j++;
ptr = strtok(NULL, ";");
}
arr[i] = a;
}
return arr;
}
My program works just fine, however, I got memory leaks for each loaded line because of the malloc(256)
, and I also got memory leak after using realloc(lines, ar_length);
I'm quite unsure why I get these leaks because isn't it supposed to "automatically free" the memory after a function runs?
How can I fix these memory leaks?
Thanks in advance.