작동하지 않는 몇 가지 배열을 채우고 화면에 내용을 인쇄하는 작은 프로그램은 다음과 같습니다할당 해제 메모리가 여기에
#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
I 이제 메모리 할당을 해제하려면 free(pl)
을 사용하면 작동하지 않습니다. 나는 또한 작동하는 free(pl.plist)
을 시도했다. 하지만 아직 할당 해제되지 않은 plistSize
의 메모리가 있습니다. 여기서 기억을 풀어주는 것은 옳은가?
'pl.plist = malloc을 (를 sizeof (ParticleList) * NP)를 쓸 수 있습니다 할당 된 메모리를 해제하기 위해;'... 정확히 emmm..how? –
'free()'가 작동하지 않는다고 어떻게 판단합니까? 나는 그 자체로 당신에게 그렇게 말할 수있는 아무것도 볼 수 없다. –
힌트 :'free'가 충돌 할 때'free' 호출 전에 코드의 다른 곳에서 잘못된 메모리 관리를 나타내는 것입니다. –