Search code examples
cesp32

Why sizeof succeeds on not yet exsisting variable?


Today I had troubles with corrupted heap on ESP32. As it turned out, bug was caused by this line:

u8x8_i2c_cmdinfo* cmdinfo = malloc(sizeof(cmdinfo));

When I meant

u8x8_i2c_cmdinfo* cmdinfo = malloc(sizeof(u8x8_i2c_cmdinfo));

It actually surpriszed me a lot that wrong version compiled at all.

Why do it work? What it actually does?


Solution

  • The code compiles because variable exists after its declaration. And this part just declared it: u8x8_i2c_cmdinfo* cmdinfo.

    You wouldn't be surprised if that worked, right?

    u8x8_i2c_cmdinfo* cmdinfo;
    cmdinfo = malloc(sizeof(cmdinfo));
    

    Keep in mind, that while your code compiles fine, it has a nasty bug. You are allocating space for the size of the pointer, most likely not what you want to do.