C 为什么代码会泄漏内存?

C 为什么代码会泄漏内存?,c,function,pointers,struct,memory-leaks,C,Function,Pointers,Struct,Memory Leaks,我想知道为什么这段代码会泄露内存?它水平翻转我的图像并将结构图像返回到我的主文件 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->wi

我想知道为什么这段代码会泄露内存?它水平翻转我的图像并将结构图像返回到我的主文件

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);
}
主文件以以下内容结尾:

for (unsigned int i = 0; i < plain.height; i++) {
    free(plain.pixels[i]);
}
free(plain.pixels);

getchar();
return 0;
for(无符号整数i=0;i

然而,我注意到,高度和宽度交换是问题的一部分,但我不知道在没有交换的情况下如何才能做到这一点。

您通过交换高度和宽度修改了
img

但是,当您释放
img
tmp
像素腾出空间时,您是在
tmp
s高度之后释放
img
。也就是说,您使用的是
img
s新高度,而不是其原始高度

若要修复,请使用
img
s width(原来的高度)将循环更改为free

for(无符号i=0;iwidth;i++){
自由(img->pixels[i]);
}

您在
tmp->pixels[i]
上使用
malloc
,但最终,您使用的是
free(img->pixels[i])
而不是
free(tmp->pixels[i])
。最后释放
tmp
时,
tmp
上所有分配的像素都将丢失。这可能就是问题所在吗?你应该读@P.P.我强迫只有一个人有1500票没有投票,210票投了。。。选择你的立场:p@Henke您是如何确定此代码泄漏内存的?如果您取消了对
turnImg
的调用,这会改变什么吗?下面是一个让代码更容易理解的提示:在输入时立即设置两个变量,
orighight
origWidth
。在所有循环和分配中只在函数中使用这两个。设置返回图像的宽度和高度。这将使您更容易看到是否在正确的位置使用了正确的值。由于交换和赋值,这个代码很难理解。@DavidSchwartz在释放
img->pixels
后,他将
img->pixels
替换为
tmp->pixels
。他在释放它们之前不会交换它们。因此,他释放了错误的人,对吗?是的,它现在起作用了。非常感谢。我不敢相信它这么简单……是的,它最终可能会让我找到这个解决方案:)
for (unsigned int i = 0; i < plain.height; i++) {
    free(plain.pixels[i]);
}
free(plain.pixels);

getchar();
return 0;
    for (unsigned i = 0; i < img->width; i++) {
        free(img->pixels[i]);
    }