這裏是一個充滿一些陣列和打印其屏幕上的內容的小程序:有免費()釋放內存不起作用
#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
這是不是釋放。在這裏釋放記憶的正確方法是什麼?
'pl.plist =的malloc(的sizeof(ParticleList)* NP);'... emmm..how到底是什麼? –
你如何判斷'free()'不起作用?我在程序本身看不到任何可以告訴你的東西。 –
提示:當'free'崩潰時,它是代碼中其他地方的內存管理不好的標誌,在調用'free'之前。 –