diff options
author | Muhammad Zahalqa <m@tryfinally.com> | 2020-08-13 20:14:28 +0300 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2020-08-13 19:16:15 +0200 |
commit | 11b9e8b36686a2862cc4db9a8c050b073ceb981e (patch) | |
tree | ea95a9d40f71a9a5ae50def747886ccc6a30dc43 | |
parent | dcfc54d767bcb2b7a9376cda3fa0fccd1aaf1626 (diff) | |
download | serenity-11b9e8b36686a2862cc4db9a8c050b073ceb981e.zip |
LibC: Some calloc() and realloc() improvements (#3108)
If the space cannot be allocated, the original memory block shall remain
unchanged and the function should return nullptr.
Also add a function attribute and some null checks.
-rw-r--r-- | Libraries/LibC/malloc.cpp | 12 | ||||
-rw-r--r-- | Libraries/LibC/stdlib.h | 2 |
2 files changed, 10 insertions, 4 deletions
diff --git a/Libraries/LibC/malloc.cpp b/Libraries/LibC/malloc.cpp index 17ddbbb1b4..72d5b5bc27 100644 --- a/Libraries/LibC/malloc.cpp +++ b/Libraries/LibC/malloc.cpp @@ -397,7 +397,8 @@ void* calloc(size_t count, size_t size) { size_t new_size = count * size; auto* ptr = malloc(new_size); - memset(ptr, 0, new_size); + if (ptr) + memset(ptr, 0, new_size); return ptr; } @@ -418,13 +419,18 @@ void* realloc(void* ptr, size_t size) { if (!ptr) return malloc(size); + if (!size) + return nullptr; + LOCKER(malloc_lock()); auto existing_allocation_size = malloc_size(ptr); if (size <= existing_allocation_size) return ptr; auto* new_ptr = malloc(size); - memcpy(new_ptr, ptr, min(existing_allocation_size, size)); - free(ptr); + if (new_ptr) { + memcpy(new_ptr, ptr, min(existing_allocation_size, size)); + free(ptr); + } return new_ptr; } diff --git a/Libraries/LibC/stdlib.h b/Libraries/LibC/stdlib.h index e9f987b3b0..fbe8d75831 100644 --- a/Libraries/LibC/stdlib.h +++ b/Libraries/LibC/stdlib.h @@ -42,7 +42,7 @@ __attribute__((malloc)) __attribute__((alloc_size(1))) void* malloc(size_t); __attribute__((malloc)) __attribute__((alloc_size(1, 2))) void* calloc(size_t nmemb, size_t); size_t malloc_size(void*); void free(void*); -void* realloc(void* ptr, size_t); +__attribute__((alloc_size(2))) void* realloc(void* ptr, size_t); char* getenv(const char* name); int putenv(char*); int unsetenv(const char*); |