为什么打印到stdout会导致`malloc():顶部大小损坏,而打印到stderr却能正常工作?

时间:2020-05-13 05:59:24

标签: c memory-management malloc stdout stderr

我具有以下功能来设置结构并从该结构中转储一些数据:

#include <stdio.h>
#include <stdlib.h>

#include "image.h"

// typedef from image.h included above, copied here for SO
typedef struct image {
    int width;
    int height;
    char *data;
} image;

image *image_new(int width, int height) {
    image *i = malloc(sizeof(image));
    i->width = width;
    i->height = height;
    // allocate space for each row
    i->data = malloc(sizeof(unsigned char) * height * width * 3);
    return i;
}

void image_dump_data(image *i) {
    for (int x = 0; x < i->width; x++) {
        for (int y = 0; y < i->height; y++) {
            // write pixel color to file
            unsigned char r = i->data[(y * i->width) + (x * 3) + 0];
            unsigned char g = i->data[(y * i->width) + (x * 3) + 1];
            unsigned char b = i->data[(y * i->width) + (x * 3) + 2];
            printf("%d %d %d ", (int)r, (int)g, (int)b);
        }
        printf("\n");
    }
}

第一次进行printf()调用后,我的代码将失败,并显示消息malloc(): corrupted top size。当我将printf()更改为fprintf(stderr, ...)时,得到了预期的输出。当我使用fprintf(stdout, ...)时,错误仍然存​​在,因此专门使用stdout的某些事情似乎导致我的代码失败。

我希望在这里包括所有相关信息,但是如有必要,here is a link to the GitHub repo包含我正在用于该项目的所有文件。

2 个答案:

答案 0 :(得分:1)

我不小心利用了未定义的行为,该行为在打印到stderr而不是stdout时会起作用(可能是由于缓冲与非缓冲输出)。在一个单独的文件中,我对结构指针的大小而不是对结构本身的malloc不好,导致分配的内存太小。直到后来,这才立即成为问题。使用valgrind进行调试时,以下几行直接将我指出了该问题:

==1417933== Invalid write of size 8
==1417933==    at 0x10A864: scene_new (scene.c:24)
==1417933==    by 0x109267: main (raytracer.c:27)
==1417933==  Address 0x4b8b160 is 0 bytes after a block of size 32 alloc'd
==1417933==    at 0x483977F: malloc (vg_replace_malloc.c:309)
==1417933==    by 0x10A823: scene_new (scene.c:23)
==1417933==    by 0x109267: main (raytracer.c:27)

答案 1 :(得分:-1)

您是否尝试过更改格式以避免转换?不确定是否有帮助,但是您可以尝试printf doc

printf("%hhu %hhu %hhu ", r, g, b);