gpt4 book ai didi

c - c 中的动态内存分配,释放在使用 malloc() 之前分配的部分内存

转载 作者:太空狗 更新时间:2023-10-29 15:24:13 24 4
gpt4 key购买 nike

有什么方法可以释放您使用 malloc() 创建的部分内存吗?

假设:-

int *temp;

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

free() 将释放所有 20 字节的内存,但假设我只需要 10 字节。我可以释放最后 10 个字节吗?

最佳答案

您应该使用标准库函数realloc。顾名思义,它重新分配一 block 内存。它的原型(prototype)是(包含在头文件 stdlib.h 中)

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

该函数将ptr 指向的内存块的大小更改为size 字节。此内存块必须由 mallocrealloccalloc 调用分配。重要的是要注意 realloc 可能会将旧 block 扩展到 size 字节,可能会保留相同的 block 并释放额外的字节,或者可能会分配一个全新的内存块,将内容从旧 block 复制到新 block ,然后释放旧 block 。

realloc 返回指向重新分配内存块的指针。如果重新分配内存失败,则返回 NULL 并且原始内存块保持不变。因此,在调用realloc 之前,您应该将ptr 的值存储在临时变量中,否则原始内存块将丢失并导致内存泄漏。此外,您不应转换 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;
}

关于c - c 中的动态内存分配,释放在使用 malloc() 之前分配的部分内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23040343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com