Search code examples
cunixpointersposixrealloc

When realloc shrinks a allocated block, where is the memory free'd?


I'm constructing a bigInt datatype which uses an array of unsigned short's. In some functions, the highest order short may or may not be used, but is always allocated just in case. To prevent endless memory consumption from basic math operations, I'd like to just realloc the array thus:

toReturn.numArray = realloc(toReturn.numArray, (sizeof(unsigned short)) * (toReturn.numElements - 1))

but I don't know if the highest order bits will be free'd (ideal) or the lowest order bits.


Solution

  • If the memory block is relocated, data will be copied from the bottom of the old buffer, up to the new size.

    If you want to preserve the top of your data, you will have to do a malloc/memmove or similar.

    How this relates to your bits depends on how you map your data into the block, I would have thought. This ought to be controllable.