1

Hi I have problem with freeing array in my code.

 int main(){
int **pole = mallocator(); ...

In main I call function which allocates memory and looks this:

int ** mallocator(){
int **pole = (int **) malloc(sizeof(int*)*RADEK);

for(int i=0; i < RADEK; i++){ 
    pole[i] = (int *) malloc(sizeof(int)*RADEK); 

 }

return pole;
}

And in the end i free it with this function:

void freedom(int **pole){

for(int i=0; i < RADEK; i++){ 
    printf("%d\n", i);
    free(pole[i]);
}
free(pole);
}

RADEK is constant with value 25. I thought it worked, but valgrind says I have 27 allocs and 26 frees and says that one block is still reachable. Any ideas on how to achieve no leaks? Thanks

EDIT:The return line shouldn't have been in for cycle that was badly copied, thanks for noticing. Also it probably was a bug of compiler. If I use gcc instead of g++ it says there are no leaks, but when I compile with g++ it says static still reachable: 72,704 even when I don't use malloc in the code.

Adam J
  • 11
  • 2
  • 2
    I don't think your `return pole;` is in right position. – MikeCAT Feb 03 '16 at 23:39
  • They say [you shouldn't cast the result of `malloc()` in C](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – MikeCAT Feb 03 '16 at 23:41
  • What operating system are you running? – Jeremy Rodi Feb 03 '16 at 23:56
  • 2
    If the `return pole` is not a pasting mistake, then your problem is not memory leak, but free some random memory. – Holsety Feb 04 '16 at 00:09
  • And, you should show your entire main function. The code you shown has 26 allocs only. – Holsety Feb 04 '16 at 00:11
  • 1) this line: ` return pole;` should be after the end of the `for()` loop, not in the middle of it. 2) in C, do not cast the returned value from `malloc()`. the return type is `void*` which can be assigned to any pointer. Casting just clutters the code making it more difficult to understand, debug, maintain. 3) always check (!=NULL) the returned value to assure the operation was successful – user3629249 Feb 04 '16 at 02:45
  • 2
    Possible duplicate of [c++ valgrind shows memory leak in hello world](http://stackoverflow.com/questions/35871265/c-valgrind-shows-memory-leak-in-hello-world) – Petr Skocik Mar 20 '16 at 13:05

1 Answers1

0

after correcting the mallocator() function, as specified in the comments.

Then the main() function can free the allocated memory via:

for( int i=0; i<RADEK; i++ )
{
    free( pole[i]);
}
free( pole );
user3629249
  • 16,402
  • 1
  • 16
  • 17