Home > other >  Can I add a local instance of a pointer to a struct with memory allocated with malloc to a global ar
Can I add a local instance of a pointer to a struct with memory allocated with malloc to a global ar

Time:05-14

Problem

Valgrind is informing me of a memory leak, however no matter what I cannot seem to figure out how I haven't freed all my allocated memory, leading to the question in my title. I won't provide my full code so I also won't attach the entire valgrind report, but I will point out where valgrind think the problem is.

Some code to further explain what is going on

assume all memory allcations are checked for error, assume while loop teminates eventually

struct s1{
  int total_s2; // assume some code initialise this to 0
  struct s2 **arr_s2;
} struct1;

struct s2{
  char *important_string
};


void add_s2_to_s1(struct s2 *struct2){
  struct1.arr_s2 = realloc(s1.arr_s2, sizeof(struct s2 *) * s1.total_s2);
  struct1.arr_s2[total_s2 - 1] = malloc(sizeof(struct s2));  // !mem lost!
  struct1.arr_s2[total_s2 - 1] = struct2;
}

// in main
while(some_string){
  struct s2 *struct2 = malloc(sizeof(*struct2));
  struct2->important_string = malloc(sizeof(some_string)   1);
  s1.total_s2  ;
  add_s2_to_s1(struct2);

  // some code to change some_string
}

for(int i = 0; i < total_s2; i  ){
  free(s1.arr_s2[i]->important_string);
  free(s1.arr_s2[i]);
}
free(s1.arr_s2);

Bit more on my understanding

Even though struct2 is technically lost each iteration of the while loop, the pointer to the memory of struct2 should be stored in the array in struct1, and thus should be able to be freed no problem.

Worst part with mem leak issues are my program is doing exactly what I want it to do right now, so it is very tempting to throw my hands in the air and move on. But I know I should fix it otherwise it might come back and bite me in the ass later.

CodePudding user response:

This line allocates some bytes and stores a pointer to those bytes in the variable struct1.arr_s2[total_s2 - 1]:

struct1.arr_s2[total_s2 - 1] = malloc(sizeof(struct s2));  // !mem lost!

This line stores a pointer to some other bytes in the variable struct1.arr_s2[total_s2 - 1]:

struct1.arr_s2[total_s2 - 1] = struct2;

As you know, a variable only has one value at a time. The variable struct1.arr_s2[total_s2 - 1] now contains the same value as the variable struct2 - it doesn't somehow remember the other value you gave it (the address of some newly allocated bytes).

  • Related