4 ms·
>"what does malloc return?" This is particularly pernicious, because it's a trick question, too. On linux, malloc always returns, it will never return NULL. Ev
by Afforess 8y ago
>"what does malloc return?"
This is particularly pernicious, because it's a trick question, too. On linux, malloc always returns, it will never return NULL. Even if you ask for 4 petabytes of memory on a 128mb system, malloc will hand you back a valid pointer for the memory.
https://scvalex.net/posts/6/ https://scvalex.net/posts/6/
- merb 8y agowell a sane answer would be that it returns a void* ptr to the allocated memory that can be casted to the needed ptr type.
- coryrc 8y agoI'm pretty sure it will fail NULL if overcommit is disabled. (And apparently other conditions: https://stackoverflow.com/questions/2248995/is-there-a-need-to-check-for-null-after-allocating-memory-when-kernel-uses-over https://stackoverflow.com/questions/2248995/is-there-a-need-... )
- Retra 8y agoIf I were asked that, I would say something like "malloc attempts to allocate some memory on the heap and return a pointer to it." If pressed for more details, I would say it depends on the allocator and that we should look at the documentation for it to find out. If that was an unacceptable answer, then I'd consider the interview a waste of time.