r/ProgrammerHumor 2d ago

Meme bugIntroducedDebugging

Post image
1.1k Upvotes

120 comments sorted by

View all comments

346

u/AdBrave2400 2d ago

Is the mistake that they're allocating 1 byte and storing in a pointer to an int which is 4 bytes?

1

u/Duck_Devs 2d ago edited 2d ago

I believe it’s compliant to have malloc(1) return memory that can fit an int.

sizeof(char) is always 1; malloc works based on sizeof.

char is allowed to be anything >= 8 bits wide

int is >= 16 bits.

In theory, you could have char and int both be 16 bits.

Edit: this is why you should always do malloc(n * sizeof(type))

Edit 2: Wikipedia (C data types article) literally states that a platform could theoretically have all int types be 64 bits, for those who doubt me.