cansi-c

Using free with pointer to middle of allocation


I have recently come across C devs recommending use cases for calling the free(void*) function, but instead of passing the original pointer returned by malloc, passing a pointer to another address which is in the middle of the original allocated block of memory.

Is this ANSI C? Where is this behavior specified? Is it portable to any compliant compiler?

Edit: FYI, the context this was presented in was in implementing BStrings, where the length of the string is stored before the pointer address, and the data is stored after. It was claimed you can free the pointer as is, which did not sound right to me.


Solution

  • The C standard (C11) says:

    7.22.3.3 The free function
    Synopsis

        #include <stdlib.h>
        void free(void *ptr);
    

    Description

    The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

    The verbiage of C23 is the same.

    So, the standard explicitly says that the behaviour is undefined. Most implementations do not handle pointers to the middle of an allocated block. There is no defined way for free() to report an 'invalid argument' error as it returns no value. Any implementation that does handle such erroneous calls to free() is not required to do so by the standard.