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?

28

u/CanardAuxEpices 2d ago

Uuuh... Actually 🤓🤓☝️☝️☝️ an int isn't 4 bytes, it's platform/compiler dependent. Assuming an int is 4 bytes will be in the majority of cases true, but it's not always the case

6

u/meat-eating-orchid 2d ago

technically, an int could even be just one byte if you are on an architecture where a byte (= smallest addressable unit) has 16 bit

3

u/CanardAuxEpices 2d ago

Yeah! But a char will always be one byte

2

u/mckenzie_keith 2d ago

We need to define terms more precisely. sizeof(char) will always be 1. But on some platforms, char is not an 8-bit type. It could actually be a 32 bit type. The c programming language does not (I believe) acknowledge or define what a byte is. But if it is an 8 bit integer type, then char will not always be one byte.

It may be better to say "octet" instead of "byte" in this type of discussion.

The implementation has to define CHAR_BIT in <limits.h>. CHAR_BIT is the number of bits in variables of type "char".

3

u/el_nora 2d ago

Fun fact, C does use the term byte all over the standard. And it is well defined. Byte is defined to be the unit that sizeof(char) is measured in. When the standard refers to bytes, they are referring to atomic divisions of memory in chunks of char.

Which does not necessarily need to be the same as an architectural byte. C requires only that their definition of byte is at least 8 bits (possibly more) and an addressable unit of memory - meaning it is some multiple of architectural bytes. Though on every platform still in use today, and not a historic curio, that multiple is 1.

1

u/mckenzie_keith 2d ago

So I am wrong about that. Oops. I guess then that one needs to define what they mean by "byte" when using it in an online discussion. The person I replied to is right, then, that char will always be one byte. But some people when they say "byte" are thinking of an 8-bit entity. Anyway, thanks for the info.

2

u/CanardAuxEpices 2d ago

You're brobably right. To be honest, I keep confusing myself with bytes and bit cause I'm french and here we use octet. Plus, my C classes starts getting quite far, but I just remembered the fun fact, I'll go check properly because it actually made me curious.

2

u/grencez 1d ago

It's kinda funny that C99 introduced int8_t and made it optional, but I'm sure there's some good reason. Basically if that type exists, then CHAR_BIT is 8. Also POSIX.1-2001 defines it that way, so most people can safely assume it.