Avoid zero-length calloc (#3280)

Using `calloc` function with a count of zero elements is implementation
defined and it may cause allocation errors on some platforms (ref #3277).
This commit fixes `jv_mem_calloc` callers to avoid undefined behavior.
This commit is contained in:
itchyny authored and GitHub committed 2025-03-04 22:33:51 +09:00
1 parent 4003202ccf
commit a8ce2ff09a
6 files changed
+28 -7

No files matched your search

+5 -2
View File
@@ -1,7 +1,8 @@
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "jv_alloc.h"
#include "jv.h"
struct nomem_handler {
jv_nomem_handler_f handler;
@@ -150,6 +151,7 @@ void* jv_mem_alloc_unguarded(size_t sz) {
}
void* jv_mem_calloc(size_t nemb, size_t sz) {
assert(nemb > 0 && sz > 0);
void* p = calloc(nemb, sz);
if (!p) {
memory_exhausted();
@@ -158,6 +160,7 @@ void* jv_mem_calloc(size_t nemb, size_t sz) {
}
void* jv_mem_calloc_unguarded(size_t nemb, size_t sz) {
assert(nemb > 0 && sz > 0);
return calloc(nemb, sz);
}