snoopy91
snoopy91

Reputation: 347

In C, is it safe to call free() on memory block which contains NULL before its end?

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!

Upvotes: 1

Views: 1164

Answers (4)

Brian Agnew
Brian Agnew

Reputation: 272417

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

Upvotes: 2

Belkacem REBBOUH
Belkacem REBBOUH

Reputation: 559

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

Upvotes: 0

Charles0429
Charles0429

Reputation: 1420

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.

Upvotes: 3

Dayal rai
Dayal rai

Reputation: 6606

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.

Upvotes: 0

Related Questions