c - 为什么代码会泄漏内存?

标签 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->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 腾出空间像素,您正在释放imgtmp的高度。也就是说,您正在使用 img s 新的高度而不是原来的高度。

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

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

关于c - 为什么代码会泄漏内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42098254/

相关文章:

c - 将信号量添加到程序中 - Linux 中的 C

c - 执行官和我;我怎样才能让它为我工作?

当行不消失时删除 data.frame 中的所有空列和行

c - C 中数组的 & 运算符定义

c - C 中的文件处理。更多命令?

c - C 中的堆栈溢出

c - rand/srand 函数在 C 中如何工作

javascript 字符、单词和空格计数函数

c - 对 malloc 返回的指针进行类型转换是更好的做法吗?

c - 包含指向自身的指针的结构,但实际上不是