我想知道为什么这段代码会泄漏内存?它水平翻转我的图像并将结构图像返回到我的主文件。
void turnImg(Image *img) {
Image *tmp = (Image*)malloc(sizeof(Image));
//swapping size between height and width
tmp->height = img->height;
img->height = img->width;
img->width = tmp->height;
//The loop is swapping every pixel from the "last" pixel to the "first" into a tmp
tmp->pixels = (Pixel**)malloc(sizeof(Pixel*)*img->height);
for (unsigned int i = 0; i < img->height; i++) {
tmp->pixels[i] = (Pixel*)malloc(sizeof(Pixel)*img->width);
for (unsigned int j = 0; j < img->width; j++) {
tmp->pixels[i][j] = img->pixels[img->width - 1 - j][img->height - 1 - i];
}
}
for (unsigned i = 0; i < img->height; i++) {
free(img->pixels[i]);
}
free(img->pixels);
//tmp gives back the pixels to img, but they are now flipped
img->pixels = tmp->pixels;
free(tmp);
}
主文件中不应该有任何问题,因为我的所有其他函数都运行良好...但这里是主文件的平静,它正在向函数发送和返回结构:
case 5:
//Flipping the image on its diagonal.
printf("Flipping the image on its diagonal...");
turnImg(&plain);
printf("Image flipped.\n");
break;
主文件结尾为:
for (unsigned int i = 0; i < plain.height; i++) {
free(plain.pixels[i]);
}
free(plain.pixels);
getchar();
return 0;
但是,我注意到高度和宽度交换是问题的一部分,但我不知道如何在没有交换的情况下做到这一点。
最佳答案
您已修改img
通过交换其高度和宽度。
但是,当你释放img
时为 tmp
腾出空间像素,您正在释放img
继 tmp
的高度。也就是说,您正在使用 img
s 新的高度而不是原来的高度。
要修复此问题,请使用 img
将循环更改为空闲。 s 宽度(这是它的旧高度)。
for (unsigned i = 0; i < img->width; i++) {
free(img->pixels[i]);
}
关于c - 为什么代码会泄漏内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42098254/