And what if we call realloc with ptr that is not NUL, but also, was not returned by an earlier call to malloc(), calloc() or realloc()?
It is plainly wrong.
A common beginner's error is attempting to use realloc()
on objects, pointers to the first element of which weren't returned by a previous call to a function of the malloc()
family. A typical example is passing an automatic array to a function which is supposed to modify its contents, possibly resize it as well by passing object's pointer to realloc
. The code would compile, but the program would likely abort. lldb
debugger would issue a message such as:
`malloc: error for object 0x7fff6fbb16d6: pointer being realloc'd was not allocated`
gdb
debugger would issue a similar, though slightly more complex message, such as:
`malloc.c:2869: mremap_chunk: Assertion `((size + offset) & (GLRO (dl_pagesize) - 1)) == 0' failed. `
`Aborted (core dumped)`
This is still a better case. By the book, behavior inferred by such calls is undefined. You may take a look at malloc.c
of any operating system. Please, also see this SO post. This reference link may also be worth reading.