Remix.run Logo
groundzeros2015 3 hours ago

I’m not a language lawyer but i think the part you are missing is about “type establishment”. (Is this a C vs C++ thing?)

Malloc returns a buffer and then you cast it to the type you want. Similarly for all memory allocators.

Punning the same region of char buffer as two different types is a bit different.

jcranmer 20 minutes ago | parent | next [-]

This gets to the heart of effective type rules, which are complex, confusing, and not properly implemented by compilers. C and C++ definitely diverge here, because C is less ambitious in its object model (which mean it just simply leaves so many details about it undiscussed).

Malloc returns memory that is uninitialized and has no type. The effective type of that memory is initialized on first use by C, whereas C++ relies on angelic nondeterminism to magically initialize the type at return type to whatever will work in the future.

amluto 3 hours ago | parent | prev [-]

> Malloc returns a buffer and then you cast it to the type you want.

You can’t cast the buffer — you’re casting the pointer.

One might argue (I’m not sure whether this is correct) that malloc allocated an array of ints and the language merely has no way to state that directly. Then you write to those ints using a char pointer, and then you access them as ints, but they’ve been ints ever since allocation.

groundzeros2015 3 hours ago | parent [-]

yes but that works not because malloc is special but because there are more relaxed types rules than suggested by the comment above.