Quicksilver
Quicksilver

Reputation: 249

Realloc implementation

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?

Upvotes: 1

Views: 1072

Answers (2)

Martin v. Löwis
Martin v. Löwis

Reputation: 127447

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.

Upvotes: 3

DigitalRoss
DigitalRoss

Reputation: 146053

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.

Upvotes: 1

Related Questions