|
|
|
|
|
by astrange
1571 days ago
|
|
You can't implement `malloc()` in C because the pointers it returns are defined to be pointers to different objects, and if you can see the implementation of `malloc` then you know it's returning pointers to the same object (the page it gets from mmap/sbrk). There's no functionality in C to actually do what it says except for the function itself. |
|
malloc itself is specified to return a void pointer, but the effective type established during assignment circumvents what would otherwise be UB via aliasing[2].
Edit: Specifically, the reasoning is:
1. Allocated objects have no declared type;
2. 6.5.6: Objects with no declared type have the type of their accessing lvalue
3. 6.5.7: Access of a stored value is valid for lvalue expressions that are type compatible with the effective type.
So there's no UB here. `malloc` itself doesn't need to know about the effective type produced by the lvalue, and C (at least C99 onwards) respects that type for strict aliasing purposes.
[1]: https://port70.net/%7Ensz/c/c11/n1570.html#6.5p6
[2]: https://port70.net/%7Ensz/c/c11/n1570.html#6.5p7