Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shrink int array C

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

like image 902
Joeri van Veen Avatar asked Aug 29 '12 19:08

Joeri van Veen


1 Answers

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.

like image 131
SirDarius Avatar answered Nov 02 '22 12:11

SirDarius