Just started to learn C and came across the following issue:
I need to shrink an integer array in C, removing elements at the end. By removing I mean freeing. The common answer is to allocate new memory for the smaller array, after which to copy all items ( -items to remove ) of the original array into the newly allocated memory, and then free() the original array.
Because I must deal with very large arrays, I'd rather skip the copying part.
Would it be possible to create a pointer variable that points to "near the end of the original array" of size "end of array - near the end", and then free that pointer?
Thanks in advance
The realloc function from the C standard library might be what you want.
In your case, it is likely to NOT perform any copy operation, because the memory manager has no reason to allocate a new memory zone. Only the difference between the old and new size might be reclaimed by the system as available memory.
Copy would occur in the case you make your array bigger, because malloc and friends do not guarantee that the memory after the 'current' zone is actually free. If it is, then it's ok, the current memory allocation will be expanded. If not, a bigger available memory zone needs to be found, and it can be allocated pretty much anywhere in memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With