Muh*_*edy 2 c memory-management realloc
我有以下代码:
#include <stdio.h>
#include <stdlib.h>
#define OUT
void getDataFromServer(OUT int** array, OUT int* size)
{
static int tmpArr[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F};
*size = sizeof tmpArr / sizeof(int);
printf("Before realloc: %p\n", *array);
*array = realloc(*array, sizeof(*array) * *size);
printf("After realloc : %p\n", *array);
int i=0;
for (; i < *size; i++)
{
(*array)[i] = tmpArr[i];
}
}
int main(void)
{
int size = 0;
int* dataFromServer = malloc(sizeof *dataFromServer);
printf("in main: %p\n", dataFromServer);
getDataFromServer(&dataFromServer, &size);
int x;
for (x=0; x < size; x++)
printf("%d ", dataFromServer[x]);
printf("\n\n");
free(dataFromServer);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
in main: 003F1708
Before realloc: 003F1708
After realloc : 003F3430
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Run Code Online (Sandbox Code Playgroud)
从输出中,realloc返回一个指向新内存地址的指针.
所以问题是,我应该明确地释放这个位置 - 除了释放原始创建的位置malloc吗?
或者它正在做上面的代码所期望的是Just expand the memory location reserved previously什么?
谢谢.
EDIT:实际上,下面的每个答案都为我提供了一个有价值的信息.因为我只能选择一个答案来接受.我选择了纠正上述代码的那个!
在你调用realloc它并返回一些指针后你应该忘记前一个指针并保持"新"指针.
如果realloc调整大小,然后realloc返回它,如果它在内存中分配了一个新空间并复制了它的先前内容,它将释放旧指针并返回一个新指针.
但是,永远不要用调用的结果覆盖旧指针realloc(正如你在代码中所做的那样):事实上,当realloc失败时它会返回NULL并且不会释放旧指针,所以,如果你要覆盖唯一的变量where你存储它,你失去了你对free内存的唯一方式,因此你有内存泄漏.因此,"规范"的呼叫方式realloc是:
/* assuming myPtr contains the malloced memory */
void * tempPtr=realloc(myPtr, newSize);
if(tempPtr==NULL)
{
/* realloc failed, handle the error and, if aborting, free myPtr */
}
else
myPtr = tempPtr;
/* ... */
/* when you no longer need it free the memory */
free(myPtr);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1079 次 |
| 最近记录: |