tags:

views:

220

answers:

2

I'm writing a simple linked list based memory manager in the form:

...Header|Block|Header|Block... with a used and free list.

If the realloc() function was asked to reduce the size of a block, is it okay to overwrite some of the trailing bytes with the header for the newly created block? The documentation I've read suggests this is 'undefined behaviour' but do applications depend on the data still being there?

+1  A: 

Sure. It has been reallocated, so now it has been released by the app and it belongs to your manager. It's normal to start clobbering it with new pointers.

DigitalRoss
+3  A: 

Most likely, the remark on undefined behavior went like this: "it is undefined to access any bytes after the end of the block when realloc returns".

Such a specification is there precisely to allow you to put a header into the trailing bytes in the implementation of realloc. That it is undefined behavior means that if an application would try to read from the bytes (that are conceptually gone), it would read your header, which would appear as garbage to the application; if it even writes, it would kill your header - so the application shouldn't do that.

Martin v. Löwis