I was once told that optimizations in the sense of dead code elimination the way clang does it could be bypassed by making a variable volatile... Wouldn't that help here as well?
volatile unsigned char *p = malloc(w * h);
...