2

假设我有以下情况(一些粗略的伪代码):

struct { 
  int i;
} x

main(){
  x** array = malloc(size of x pointer); // pointer to an array of pointers of type x
  int* size = current size of x // (initally 0)
  add(array, size);
}

add(x** array, int* size){ // adds one actual element to the array
  x** temp = realloc(array, (*size)+1); // increase the array size by one
  free(array);
  array = temp;

  // My question is targeted here
  array[*size] = malloc(size of x); // makes a pointer to the value 
  array[*size]->i = size;
  *size++;  
}

我的问题是:一旦 add() 完成,存储在数组中的指针的值是否会随着函数调用堆栈一起消失,因为我在 func() 中分配了它们?我担心他们可能会,在这种情况下,我会有更好的方法来做事吗?

4

1 回答 1

1

不,他们没有。它们一直存在,直到返回的指针malloc()被传递给相应的free()函数。malloc()如果该函数的工作方式与自动数组相同,则该函数的存在将毫无意义。

编辑:旁注。当@Ancurio 指向它时,您错误地释放了先前返回的指针后面的内存,该指针malloc()在当时是无效的,因为realloc()它已被使用。不要那样做。realloc()正常工作。)

于 2012-10-21T07:13:38.640 回答