realloc的临时指针留下的垃圾变量

  • 本文关键字:变量 指针 realloc c
  • 更新时间 :
  • 英文 :


在使用realloc时,最好检查是否存在空指针,如:

int *tempPtr=realloc(ptr1,size);
if(tempPtr==NULL){
fprintf(stderr,"Error allocating memory at line %dn",__LINE__);
exit(-1);
}
ptr1=tempPtr;

这种方法的问题是,它创建了一个新变量,如果它不在一个快速临时块中,它只会在程序结束时被销毁。

有没有办法销毁这个变量?

你可以把这些表达式放在它自己的块作用域中。本质上只是将表达式封装在大括号中,例如:

{
int *tmpptr = realloc(ptr1, size);
if (tmpptr == NULL) {
panic("allocation failed");
}
ptr1 = tmpptr;
}
// Continue executing code here
// note that moving forwards from here, tmpptr is out of scope and cannot be used.

最新更新