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.
When you allocate something on the heap, pretty much every implementation out there requires more data to be allocated in addition to the user data. The bytes you see through the malloc
& friends interface is just the user data. A common way for the standard library/OS to implement heap allocation is to first allocate a segment header, followed by the data.
This means that to the immediate "left" (lower addresses) of the data part of the segment sits the header. Leaving a gap there between header and data doesn't make any sense. Rather, you'd have to move the whole thing to a new memory location.
but these methods don't suit my needs.
And what are those needs, exactly? When using dynamic memory we must be aware that:
For example:
char *a = malloc(10);
char *b = realloc(a, 8);
Probably consumes much more RAM memory overall than lets say char c[12];
. And it will almost certainly be some ~100 to 1000 times slower.
It is also quite likely that the execution time overhead involved in calling realloc
is far more expensive than a memcpy
/memmove
call.
So what is the actual problem you are trying to solve here?