很难说在不知道是什么的情况下这样做是否可以。但是你可以从这个开始......realloc
I do something
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *temp,count;
}foo;
extern char etext, edata, end;
int main()
{
printf("Heap before first malloc %p\n", sbrk(0));
foo *fake = malloc(1*sizeof(foo));
printf("heap after first malloc %p\n", sbrk(0));
fake->count = 0;
++(fake->count);
fake->temp = malloc((fake->count)*sizeof(int));
printf("heap after second malloc %p\n", sbrk(0));
fake->count += 2;
fake->temp = realloc(fake->temp, (fake->count) * sizeof(int));
printf("count %d\n", fake->count);
printf("heap after realloc %p\n", sbrk(0));
printf("program text segment(etext) %10p\n", &etext);
printf("initialized data segment(edata) %10p\n", &edata);
printf("uninitialized data segment (end) %10p\n", &end);
return 0;
}
这也将输出您的堆地址。
Heap before first malloc 0x239b000
heap after first malloc 0x23bc000
heap after second malloc 0x23bc000
count 3
heap after realloc 0x23bc000
program text segment(etext) 0x400816
initialized data segment(edata) 0x600bc4
uninitialized data segment (end) 0x600bd8
你不需要为malloc()
.
考虑calloc()
清除你的记忆。在重新分配时,您可能会得到错误初始化的内存块。(就像最近释放的块)。
realloc()
在使用它之前总是检查它的返回值。那么失败的机会realloc()
是相当高的malloc()
。