我知道realloc()
有两种方式。第一种方式是在新地址上分配内存并释放旧内存。第二种方式是在同一地址上分配内存,这样你只需要释放该地址即可。因此,在这两种情况下,你只需释放由realloc()
分配的内存地址。但如果realloc()
返回NULL,那么我需要像这样释放旧内存吗?:
//so in the first way, as b would be another address, a would be freed and if b is NULL it is no necessary to free it. But, if it follows second way, b will be same address as a and if it is NULL, I need to free old memory (a), right?
int *a = (int*)malloc(sizeof(int));
int *b = (int*)realloc(a,sizeof(int)*3);
if(!b){
free(a);
}
realloc
函数规定了其行为:如果无法为新对象分配内存,则不会释放旧对象,其值保持不变。 - Jonathan Leffler