编辑:由于 coderredoc 建议的表述不当,我将关闭这个问题。
我有一个自由函数的问题,我错误地将位置的地址作为参数。
void freeMemory(Stack stp, int n){
for(int i=0; i<n; i++){
free(&(stp.signals[n].intervals));
}
free(stp.signals);
}
这是正确的代码(查看下面的更多信息)
void freeMemory(Stack stp, int n){
for(int i=0; i<n; i++){
free(stp.signals[n].intervals);
}
free(stp.signals);
}
最佳答案
永远记住一件事,您将把使用 malloc
分配的任何内容传递给 free
及其 friend 。
这里传了free(&(stp.signals[i].intervals));
为什么要传stp.signals[i].intervals的地址
它是 stp.signals[i].intervals
,其中包含已分配 block 的地址。 (刚刚使用*alloc
创建的内存块的起始地址)所以free(stp.signals[i].intervals)
是释放它的正确方法。
准确地说,你在这里所做的是未定义的行为。
来自标准7.22.3.3p2
The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.
关于C编程: Freeing nested multidimensional arrays inside structs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48778911/