2 ms·
I don't know why you think magic is needed to implement malloc(). It can be readily implemented in C. It controls a range of memory and doles out chunks upon re
by kevin_thibedeau 6y ago
I don't know why you think magic is needed to implement malloc(). It can be readily implemented in C. It controls a range of memory and doles out chunks upon request. Doing that in a system with an MMU requires hardware interaction to handle virtual memory but that isn't outside of the wheelhouse for C.
- pjmlp 6y agoIt is outside of what ISO C defines and requires either language extensions or external Assembly.
- astrange 6y agomalloc() in C returns a new memory object each time you call it (I forget the exact wording here). There is no operation in the C standard that creates new memory objects; the only way to do it is by calling malloc(). And obviously, this doesn't let you implement it.
- kevin_thibedeau 6y agoYou don't have to "create a new memory object". C doesn't say how malloc() is implemented. It is perfectly valid to have a statically defined array and have malloc() pull from that. The majority of the computers in the world do this. You're conflating limitations imposed by layers of OS infrastructure with limitations of C.
- astrange 6y agoI'm not talking about any OS concept, but about the concept of how memory works in the virtual machine defined by the C standard. That implementation isn't compliant just because it works; if an undefined behavior checker could see into the malloc implementation, it would see that it's returning pointers inside the same object, which conflicts with the (impossible to implement) rule that malloc returns pointers to different objects. The practical consequence of this is malloc is kept in a different library and not inlined into callers, and asan doesn't work with custom allocators unless you tell it they behave like malloc.