This is a followup to Can a char array be used with any data type?
I know about dynamic memory and common implementations of malloc, references can be found on wikipedia. I also know that the pointer returned by malloc can be cast to whatever the programmer wants, without even a warning because the standard states in 6.3.2.3 Pointers §1
A pointer to void may be converted to or from a pointer to any incomplete or object type. A pointer to any incomplete or object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
The question is assuming I have a freestanding environment without malloc
and free
, how can I build in conformant C an implementation of those two functions?
If I take some freedom regarding the standard, it is easy:
- start with a large character array
- use a reasonably large alignment (8 should be enough for many architectures)
- implement an algorithm that returns addresses from that array, at that alignment, keeping track of what has been allocated - nice examples can be found in malloc implementation?
The problem is that the effective type of the pointers returned by that implementation will still be char *
And standard says in same paragraph § 7
A pointer to an object or incomplete type may be converted to a pointer to a different object or incomplete type. If the resulting pointer is not correctly aligned for the pointed-to type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer.
That does not seem to allow me to pretend that what was declared as simple characters can magically contains another type, and even different types in different part of this array or at different moments in same part. Said differently dereferencing such pointers seem undefined behaviour with a strict interpretation of standard. That is why common idioms use memcpy
instead of aliasing when you get a byte representation of an object in a string buffer, for example when you read it from a network stream.
So how can I build a conformant implementation of malloc in pure C???