c中的动态内存分配,释放使用malloc()之前分配的部分内存 [英] dynamic memory allocation in c , free some part of memory that is allocated before using malloc()

查看:174
本文介绍了c中的动态内存分配,释放使用malloc()之前分配的部分内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法可以释放通过使用malloc()创建的部分内存?

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

假设:-

int *temp;

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

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

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

推荐答案

您应该使用标准库函数 realloc 。顾名思义,它重新分配了一块内存。其原型是(包含在标题 stdlib.h 中)

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);

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

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

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;
}

这篇关于c中的动态内存分配,释放使用malloc()之前分配的部分内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆