Question: I have the following functions to set up a struct and to dump some data from the struct:

```cpp
#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");
    }
}

```

As soon as the first `printf()` call is made, my code fails with the message `malloc(): corrupted top size`. When I change `printf()` to `fprintf(stderr, ...)` I get the intended output. The error persists when I use `fprintf(stdout, ...)`, so something specifically about using `stdout` seems to be causing my code to fail.

I hope to have included all the relevant information here, but if necessary, [here is a link to the GitHub repo](https://github.com/nsilvestri/the-raytracers/tree/c/c) with all the files I am using with this project.

Answer: 
I was accidentally exploiting undefined behavior that happens to work when printing to stderr but not stdout (possibly because of buffered vs. unbuffered output). In a separate file I had a bad malloc to the size of a struct pointer, instead of the struct itself, causing the allocated memory to be too small. This didn't immediately manifest as a problem until later. When debugging with `valgrind` the following lines pointed me directly to the problem:

```
==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)

```
Have you tried changing your format to avoid the cast? Not sure if it helps but you could try [printf doc](https://www.cplusplus.com/reference/cstdio/printf/).

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

```