Saturday, December 31, 2011

Leak or nt ?

char *p=NULL;
p = (char *) malloc(10);
p++;
free(p);
What happens, is there a leak?? are 10 bytes freed??

1 comment:

  1. The answer needs little understanding of C runtime (CRT) memory management. malloc() takes size of memory to allocate, but free() does not. So, when someone sends a pointer to free() method, CRT should be able to know the amount of memory to be released. This is what I would like to refer to as 'metadata'.

    When a memory allocation for 'n' bytes requested by program, CRT internally allocates 'n' + 'm' bytes. Where 'm' bytes are for its metadata like how much is allocated, etc. CRT fills in 'm' bytes of metadata and returns the pointer by 'm' byte offset to the program. When programs calls free, CRT simply subtracts 'm' from the given address to locate metadata for that allocation.

    Here in this code, we are passing a pointer shifted by sizeof(char). So, the metadata it reads is not correct. At this time, the behavior depends really on CRT.

    Many legacy CRTs just do not accommodate such 'bad' programs, and result in unpredictable behavior (including program crashes).

    I believe CRT can keep fixed byte value at fixed offset with in metadta (cookie?). Check the fixed value at the fixed offset and make sure the metadata read is correct. If it is not, it can simply return error 'invalid pointer'.

    ReplyDelete