为什么代码会泄漏内存?

时间:2017-02-07 19:25:15

标签: c function pointers struct memory-leaks

我想知道为什么代码的这种小安静会泄漏内存?它水平翻转我的图像并将struct Image返回到我的主文件。

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;

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

1 个答案:

答案 0 :(得分:3)

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

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

要修复,请使用img的宽度(这是它的旧高度)将循环更改为空闲。

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