1

If I use malloc() to allocate myself a block of memory, assign NULL to a memory address which is within but not at the end of this block, and then call free() on this block, will I be successful in freeing the entire block, or only the part of the block up to NULL? In other words, does free() rely on NULL-termination to identify the end of a memory block, or is there some other internal method?

I am aware that this question only really applies to memory allocated for pointers (when NULL actually means something other than all bits zero.)

For example:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char **myBlock = malloc(20 * sizeof(char *));
    myBlock[10] = NULL;
    free(myBlock);
    return 0;
}

Will this code free 10 * sizeof(char *) or 20 * sizeof(char *)?

Many thanks in advance!

snoopy91
  • 337
  • 3
  • 12

4 Answers4

3

function malloc will use a struct to manage the memory it allocates

   struct mem_control_block { 
    int is_available;    
    int size;            //the actually size allocated
    };

So, free function will also use the variable size in mem_control_block to free the memory buffer. Thus Null will not affect.

Charles0429
  • 1,406
  • 5
  • 15
  • 31
  • Real malloc implementations are likely to use a bit in the size word to indicate whether the block is allocated. – Jim Balter Jul 09 '13 at 09:51
  • I like this answer because it teaches me something about malloc()/free() implementations in general as well as answering my question. – snoopy91 Jul 09 '13 at 13:01
2

free() is not aware of its contents, so the answer is yes. free() will free the complete block of memory allocated via malloc()

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
0

free uses that pointer only which is returned from malloc.This pointer have information of memory block only not about content on this memory.So free have nothing to do with NULL.

Dayal rai
  • 6,548
  • 22
  • 29
0

The memory allocation is based on a kernel independent implementation on Glibc for example, and the OS will always take back the memory after the program exists, and calling free() on the pointer will free the entire block no matter what you put into it.

if you want a more detailed explanation you can take a look at the borrowed malloc() thanks tomelm.

The memory allocation keeps a reference of the allocated memory chunk and the length (and nothing more) if you free() it you will get back :

20 * sizeof(char *) 

Cheers