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.

其他提示

Have you thought about using realloc ?

int main(void)
{
    int *array = NULL, *tmp;

    if(!(array = malloc(5 * sizeof(int)))) return 1;
    if(!(tmp = realloc(array, 2*sizeof(int)))) 
    {
        free(array);
        return 1;
    }
    array = tmp;
}

You can do this without the tmp pointer and just have array = realloc(array, 2*sizeof(int)))) but that could result in problems later down the road.

It's possible to design a memory manager that would make that possible, but none of the commonly used memory managers have this property. You could write your own mm and use it for these arrays.

I would use realloc. Realloc may copy the memory, but this could still be more efficient than rolling your own memory management to combat the problem of copying.

Some will tell you that no well-behaved C library will copy when the resulting size is smaller. They are probably right. However, I don't use or write commercial C libraries, so as far as I'm concerned the claim is unsubstantiated.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top