[PATCH] D63668: [Support] Improve zero-size allocation with safe_malloc, etc.

Alex Brachet via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Sun Jun 23 22:17:02 PDT 2019


abrachet added a comment.

> It isn't. It is implementation-defined

You're right it isn't undefined as in nondeterministic, disregard this then.

> `malloc` and friends are supposed to succeed when asked for 0 bytes except when there is insufficient space

I don't know of a situation where I would want to call malloc to allocate 0, which is why I thought assert made more sense, it's not about rights of calling malloc(3). If my code calls safe_malloc(0), I want to know about it, and the assert also solves aborting and printing a no memory error when `errno != ENOMEM`.

Just a quick grep of only safe_malloc, it seems like none of its clients would ever call it with 0 in a normal circumstance, although I may be wrong here.

For reference, GNU's widely internally used xmalloc which is analogous to this one in its contract does the same as you propose, it has an `if (size == 0) size = 1;` at the beginning. libcxx also does this for its implementation of `new` and I assume other C++ STL implementations do the same, so almost all memory allocated in llvm (assuming make_unique and unique_ptr::unique_ptr call new) will not notify us of asking for 0 bytes. For more (arguably useless) reference, mmap(2) which is also widely used in the code base (at least in my experience but only for file IO) does not allow length to be 0.

I would wait to see what other reviewers think. I just figured I would throw in the `assert(Sz)` idea, but maybe I'm the only one who thinks it makes sense :)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63668/new/

https://reviews.llvm.org/D63668





More information about the llvm-commits mailing list