dynamic memory allocation in c , free some part of memory that is allocated before using malloc()

北城余情 提交于 2020-08-27 10:08:18

问题


Is there any way to free some part of memory you created by using malloc();

suppose:-

int *temp;

temp = ( int *) malloc ( 10 * sizeof(int));
free(temp);

free() will release all 20 byte of memory but suppose i only need 10 bytes. Can i free last 10 bytes.


回答1:


You should use the standard library function realloc. As the name suggests, it reallocates a block of memory. Its prototype is (contained in the header stdlib.h)

 void *realloc(void *ptr, size_t size);

The function changes the size of the memory block pointed to by ptr to size bytes. This memory block must have been allocated by a malloc, realloc or calloc call. It is important to note that realloc may extend the older block to size bytes, may keep the same block and free the extra bytes, or may allocate an entirely new block of memory, copy the content from the older block to the newer block, and then free the older block.

realloc returns a pointer to the block of reallocated memory. If it fails to reallocate memory, then it returns NULL and the original block of memory is left untouched. Therefore, you should store the value of ptr in a temp variable before calling realloc else original memory block will be lost and cause memory leak. Also, you should not cast the result of malloc - Do I cast the result of malloc?

// allocate memory for 10 integers
int *arr = malloc(10 * sizeof *arr);
// check arr for NULL in case malloc fails

// save the value of arr in temp in case
// realloc fails
int *temp = arr;  

// realloc may keep the same block of memory
// and free the memory for the extra 5 elements
// or may allocate a new block for 5 elements,
// copy the first five elements from the older block to the
// newer block and then free the older block
arr = realloc(arr, 5 * sizeof *arr);
if(arr == NULL) {
    // realloc failed
    arr = temp;
}



回答2:


You can use realloc function provided by the standard c library.

C99 Standard 7.20.3.4-1: The realloc function:

The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object shall be the same as that of the old object prior to deallocation, up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values.



来源:https://stackoverflow.com/questions/23040343/dynamic-memory-allocation-in-c-free-some-part-of-memory-that-is-allocated-befo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!