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.
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 );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.