Question

I am not sure when to call free? Can you help me with this?

Here is sample code:

char *array[1000];
for( i < 100){ //its example, it isnt correct syntax
        if(i%2 == 0){
           array[i] = someMethod(i);
        }else{
           array[i] = "BLABLABLA";
        }
}

char * someMethod(int i){
        char *pointer;
        pointer = malloc(i); // some lenght

.
.
.
.
.

       return pointer;
}

And now, I want to use free and delete all heap-allocated memory, when I have finished using the memory to prevent memory leaks, How can i do this?

free(array); doesn't work, reporting

attempt to free non-heap object

Was it helpful?

Solution

You will need to call free for each of the elements of array. array is a static array(which is also the error you get attempt to free non-heap object) and that is why you can not free it. It's elements on the other hand are dynamically allocated and you can and should free them. Write a simple cycle and call free for the elements of array in it.

EDIT: actually you can call free only on the dynamically allocated elements of array. As you assign string literals to some of the elements and allocated memory dynamically for others(using malloc), you will have to use a helper array where you store a flag for each element that indicates if it is dynamically allocated or points to a string literal. After that only free the dynamically allocated elements in a cycle.

OTHER TIPS

You can (really should) have exactly one call to free for each call to malloc.

array[i] = someMethod(i);

should therefore be (later) paired with

free(array[i]);

This won't work however because

array[i] = "BLABLABLA";

assigns some elements to point to string literals. You didn't allocate memory for these so can't free them.

You'll need to either remember which elements were dynamically allocated or allocate memory for the elements that currently contain literals

array[i] = strdup("BLABLABLA");

You have to free all the elements.

for( i < 100){
 if(i%2 == 0)
   free(array[i]);
 i++;
}

But in this way, the whole array will not be freed. as you have assigned string literals to some of them, that can not be freed. You can only free memories that are dynamically allocated like using malloc or calloc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top