c++cmemory-management

C and C++: Freeing PART of an allocated pointer


Let's say I have a pointer allocated to hold 4096 bytes. How would one deallocate the last 1024 bytes in C? What about in C++? What if, instead, I wanted to deallocate the first 1024 bytes, and keep the rest (in both languages)? What about deallocating from the middle (it seems to me that this would require splitting it into two pointers, before and after the deallocated region).


Solution

  • If you have n bytes of mallocated memory, you can realloc m bytes (where m < n) and thus throw away the last n-m bytes.

    To throw away from the beginning, you can malloc a new, smaller buffer and memcpy the bytes you want and then free the original.

    The latter option is also available using C++ new and delete. It can also emulate the first realloc case.