1
votes

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.

1
I don't think your return pole; is in right position.MikeCAT
What operating system are you running?Jeremy Rodi
If the return pole is not a pasting mistake, then your problem is not memory leak, but free some random memory.Holsety

1 Answers

0
votes

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 );