有没有办法通过使用malloc()来释放你创建的一部分内存?
假设:
int *temp;
temp = ( int *) malloc ( 10 * sizeof(int));
free(temp);
free()函数将释放所有20个字节的内存,但是如果我只需要10个字节,我能否仅释放最后10个字节呢。
有没有办法通过使用malloc()来释放你创建的一部分内存?
假设:
int *temp;
temp = ( int *) malloc ( 10 * sizeof(int));
free(temp);
free()函数将释放所有20个字节的内存,但是如果我只需要10个字节,我能否仅释放最后10个字节呢。
您应该使用标准库函数realloc
。顾名思义,它重新分配内存块。其原型在头文件stdlib.h
中。
void *realloc(void *ptr, size_t size);
ptr
指向的内存块的大小为size
字节。该内存块必须已经通过malloc
、realloc
或calloc
调用进行了分配。需要注意的是,realloc
可能会将旧的块扩展到size
字节,也可能保留相同的块并释放额外的字节,或者可能会分配一个全新的内存块,将旧块中的内容复制到新块中,然后free
掉旧块。
realloc
返回指向重新分配的内存块的指针。如果它无法重新分配内存,则返回NULL并且原始内存块不受影响。因此,在调用realloc
之前,应将ptr
的值存储在一个临时变量中,否则原始内存块将会丢失并导致内存泄漏。此外,您不应对malloc
的结果进行强制转换-我需要对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;
}
realloc
函数。realloc
不一定会释放使用 malloc
分配的内存的一部分;它可能选择分配一个新的块,复制相关数据,然后释放旧块的全部内容。 - sapi
realloc
的存在就是为了实现这个目的。 - GoldRoger