【发布时间】:2012-10-11 08:05:53
【问题描述】:
假设我有以下情况(一些粗略的伪代码):
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() 中分配了它们?我担心他们可能会,在这种情况下,我会有更好的方法来做事吗?
【问题讨论】:
-
我不认为你应该在重新分配内存后释放它..
-
@Ancurio 对自己一点更加自信,因为你是完全正确的。至少他重新分配到一个临时的而不是蒙蔽他的数组,如果重新分配失败,可能会泄漏它。他没有检查这个,但它是伪代码,它的一半在那里,所以至少是这样。
标签: c arrays pointers memory-management function-call