I understand that the C standard library allows for the resizing of a memory allocation through the use of the realloc function, like in the following example:
char *a = malloc(10);
char *b = realloc(a, 8);
In this case, a and b could potentially be equal, and the allocation has effectively been shrunk by two bytes from the right.
However, I'm wondering if there's a way to shrink a memory allocation from the left, something like this:
char *a = malloc(10);
char *b = /* ... */; // shrink a from the left by 2 bytes
Where (a + 2) == b
, and the original 2 bytes at the start of a are now free for the allocator to use. This should happen without having to copy the data to a new location in memory. Just shrink the allocation.
I'm aware that using realloc to shrink the memory from the right or manually copying the data to a new, smaller allocation might be an option, but these methods don't suit my needs.
Is there any way to achieve this using C's standard library or any other library that provides this functionality?
I'm not asking for 100% guarantee, realloc also could return a pointer to a different location, but it is likely that it will.
Thank you in advance for your insights.
I could shift all bytes to the left and try to shrink, but it involves copying.