我有以下函数来建立一个结构体,并从结构体中转储一些数据。
#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
似乎导致我的代码失败。
我希望在这里包含所有相关信息,但如果有必要。这里是GitHub repo的链接。 和我在这个项目中使用的所有文件。
我不小心利用了未定义的行为,这种行为在打印到stderr而不是stdout时发生了工作(可能是因为缓冲和非缓冲输出)。在一个单独的文件中,我有一个坏的malloc到一个struct指针的大小,而不是struct本身,导致分配的内存太小。这直到后来才立即表现为一个问题。当使用 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)
你有没有试过改变你的格式来避免投稿?不知道是否有帮助,但你可以尝试 printf doc.
printf("%hhu %hhu %hhu ", r, g, b);