用free()释放内存不起作用 [英] Deallocate memory with free() does not work
问题描述
这是一个小程序,它填充一些数组并将其内容打印在屏幕上:
Here is a small program which fills some arrays and prints its content on the screen:
#include <stdlib.h>
#include <stdio.h>
typedef struct{
double **plist;
int plistSize;
} ParticleList;
void sendPar(int *n, int np){
// allocate memory for struct pl
ParticleList pl;
// allocate memory for ParticleList np times
pl.plist = malloc(sizeof(ParticleList) * np);
// allocate memory for lists of size n[k]
for(int k=0; k<np; k++){
pl.plist[k] = malloc(sizeof(double) * n[k]);
}
// write some data to the list
for(int k=0; k<np; k++){
for(int l=0; l<n[k]; l++){
pl.plist[k][l] = 100000*k+100*l;
}
pl.plistSize = n[k];
}
// print data to check
for(int k=0; k<np; k++){
printf("Listsize: %d\n", n[k]);
for(int l=0; l<n[k]; l++){
printf("Processor %d, Entry %d, Value %lf\n", k, l, pl.plist[k][l]);
}
}
free(pl.plist);
}
int main(){
int np = 3;
int n[np];
n[0] = 2;
n[1] = 4;
n[2] = 7;
sendPar(n, np);
}
这是输出:
Listsize: 2
Processor 0, Entry 0, Value 0.000000
Processor 0, Entry 1, Value 100.000000
Listsize: 4
Processor 1, Entry 0, Value 100000.000000
Processor 1, Entry 1, Value 100100.000000
Processor 1, Entry 2, Value 100200.000000
Processor 1, Entry 3, Value 100300.000000
Listsize: 7
Processor 2, Entry 0, Value 200000.000000
Processor 2, Entry 1, Value 200100.000000
Processor 2, Entry 2, Value 200200.000000
Processor 2, Entry 3, Value 200300.000000
Processor 2, Entry 4, Value 200400.000000
Processor 2, Entry 5, Value 200500.000000
如果我现在想取消分配内存,则使用free(pl)
不起作用.我也尝试了free(pl.plist)
,它可以工作.但是比起我,我仍然有未释放的plistSize
内存.在这里释放内存的正确方法是什么?
If I now want to deallocate the memory, using free(pl)
does not work. I tried also free(pl.plist)
which does work. But than I have still memory of plistSize
which is not deallocated. What is the right thing to free the memory here?
推荐答案
此内存分配
pl.plist = malloc(sizeof(ParticleList) * np);
^^^^^^^^^^^^^^^^^^^
没有道理.我想你是说
pl.plist = malloc( sizeof( double * ) * np);
^^^^^^^^^^^^^^^^
此循环中的最后一条语句
The last statement in this loop
// write some data to the list
for(int k=0; k<np; k++){
for(int l=0; l<n[k]; l++){
pl.plist[k][l] = 100000*k+100*l;
}
pl.plistSize = n[k];
^^^^^^^^^^^^^^^^^^^^
}
也没有意义,因为标量对象pl.plistSize
在外循环的每次迭代中都会被覆盖.
also does not make sense because the scalar object pl.plistSize
is overwritten in each iteration of the outer loop.
要释放分配的内存,您可以写
To free the allocated memory you can write
for(int k=0; k<np; k++){
free( pl.plist[k] )
}
free( pl.plist );
这篇关于用free()释放内存不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!