[PATCH] D63668: [Support] Improve zero-size allocation with safe_malloc, etc.
Andus Yu via Phabricator via llvm-commits
llvm-commits at lists.llvm.org
Fri Jun 21 13:32:16 PDT 2019
andusy created this revision.
andusy added reviewers: hubert.reinterpretcast, xingxue, jasonliu.
andusy added a project: LLVM.
Herald added a subscriber: jsji.
The current implementations of the memory allocation functions mistake a `nullptr` returned from `std::malloc`, `std::calloc`, or `std::realloc` as a failure. The behaviour for each of `std::malloc`, `std::calloc`, and `std::realloc` when the size is 0 is implementation defined, and may return a `nullptr`.
If the system function returns `nullptr`, check if the size is 0 and return a non-null pointer using malloc.
Repository:
rG LLVM Github Monorepo
https://reviews.llvm.org/D63668
Files:
llvm/include/llvm/Support/MemAlloc.h
Index: llvm/include/llvm/Support/MemAlloc.h
===================================================================
--- llvm/include/llvm/Support/MemAlloc.h
+++ llvm/include/llvm/Support/MemAlloc.h
@@ -24,23 +24,32 @@
LLVM_ATTRIBUTE_RETURNS_NONNULL inline void *safe_malloc(size_t Sz) {
void *Result = std::malloc(Sz);
- if (Result == nullptr)
+ if (Result == nullptr) {
+ if (Sz == 0)
+ return safe_malloc(1);
report_bad_alloc_error("Allocation failed");
+ }
return Result;
}
LLVM_ATTRIBUTE_RETURNS_NONNULL inline void *safe_calloc(size_t Count,
size_t Sz) {
void *Result = std::calloc(Count, Sz);
- if (Result == nullptr)
+ if (Result == nullptr) {
+ if (Count == 0 || Sz == 0)
+ return safe_malloc(1);
report_bad_alloc_error("Allocation failed");
+ }
return Result;
}
LLVM_ATTRIBUTE_RETURNS_NONNULL inline void *safe_realloc(void *Ptr, size_t Sz) {
void *Result = std::realloc(Ptr, Sz);
- if (Result == nullptr)
+ if (Result == nullptr) {
+ if (Sz == 0)
+ return safe_malloc(1);
report_bad_alloc_error("Allocation failed");
+ }
return Result;
}
-------------- next part --------------
A non-text attachment was scrubbed...
Name: D63668.206050.patch
Type: text/x-patch
Size: 1181 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20190621/1961e777/attachment.bin>
More information about the llvm-commits
mailing list