我正在使用valgrind检查代码中的内存泄漏。
我有这个结构:
typedef struct apartment_t* Apartment;
struct apartment_t {
SquareType** squares;
int width;
int length;
int price;
};
使用它的功能:
Apartment apartmentCreate(SquareType** squares, int length,
int width, int price){
if(squares == NULL || length<=0 || width<=0 || price<0)
return NULL;
Apartment newApartment=malloc(sizeof(*newApartment));
if(newApartment==NULL)
return NULL;
newApartment->length = length;
newApartment->width = width;
newApartment->price = price;
SquareType** newSquares=malloc(sizeof(*newSquares)*length);
if(newSquares==NULL){
free(newApartment);
return NULL;
}
for (int i=0;i<length;i++) {
newSquares[i] = malloc(sizeof(*newSquares[i])*width);
if (newSquares[i] == NULL) {
for (int j=i;j>=0;j--)
free(newSquares[j]);
newSquares = NULL;
free(newApartment);
return NULL;
}
}
for(int i=0;i<length;i++){
for(int j=0;j<width;j++){
newSquares[i][j]=squares[i][j];
}
}
newApartment->squares=newSquares;
newSquares=NULL;
return newApartment;
}
Valgrind发现了两个内存泄漏,但是当我尝试在最后释放(newSquares)时(newApartment->squares=newSquares;
之后)它没有显示内存泄漏,但却给了我Segmentation Fault。我错过了什么?谢谢!