Search code examples
cpointersmemoryfree

Question about free function and memory allocation ( C )


I'm trying to understand and pointers and memory allocation in C. So I have these lines of C code:

int *a=0; // a pointer which points to 0
a = (int*)malloc(5*sizeof(int));  // now the pointers a points to the adress of our allocated memory, right ?
if (a == 0) 
{
   fprintf(stderr, "Error\n");
   exit(EXIT_FAILURE);
}
printf("The value of a is %p\n", a); // this is the adress of our allocated memory
a=readArray(5); // a function which reads and array // What happens here? I read an array in that memory which I allocated, right ?
printf("Now the value of a is: %p\n", a); // Now the adress is the adress of first array element, right?
if (a != 0)
{
   free(a);
   a=0;
}

The output of this program is:

The value of a is 0x7ff780c03160
Now the value of a is: 0x7ff780c03180

Now I need pick an answer about the call of free function.

1. Deallocates the both allocated memory zones.
2. Deallocates the memory starting at adress 0x7ff780c03180 and fill that zone with zeros.
3. Deallocates the memory starting at adress 0x7ff780c03180
4. Deallocates the memory starting at adress 0x7ff780c03160

From what I read about free function, it deallocates the whole memory and it's recommended to initialize the pointer with 0. So I think the answer is the first variant, 1. Am I right ?


Solution

  • Nope, free won't deallocate more than the allocated pointer passed to it. The correct answer from your list is 3. free will deallocate the memory pointed by a at that point in time and that's it. It won't fill that memory zone with zero or anything else.

    Also, when you readArray(5), you create allocate new memory and leave aside the old allocated one before. So what you are doing step-by-step:

    1. Allocated some memory (let's call it X) using malloc and store its address in variable a.
    2. Call readArray which will allocate some other memory (let's call it Y) and store its address in a.
    3. Free the memory which is stored in a, which is the Y allocated memory chunk.

    Now the memory labeled X will be dangling, meaning that you don't have any reference to it and you have no ways of deallocating it. It's just allocated memory which cannot be reached anymore, as you lost the pointer to it.