Assert allocating non-zero size memory

Allocating zero size memory results in implementation-defined behavior:

  man:malloc(3) :
    If size is 0, then malloc() returns either NULL, or a unique pointer
    value that can later be successfully passed to free().
This commit is contained in:
Christian Göttsche 2020-10-05 12:49:01 +02:00
parent 0db398d4c3
commit 577416d1a9
2 changed files with 7 additions and 7 deletions

View File

@ -38,7 +38,7 @@ Meter* Meter_new(struct ProcessList_* pl, int param, const MeterClass* type) {
this->param = param; this->param = param;
this->pl = pl; this->pl = pl;
this->curItems = type->maxItems; this->curItems = type->maxItems;
this->values = xCalloc(type->maxItems, sizeof(double)); this->values = type->maxItems ? xCalloc(type->maxItems, sizeof(double)) : NULL;
this->total = type->total; this->total = type->total;
this->caption = xStrdup(type->caption); this->caption = xStrdup(type->caption);
if (Meter_initFn(this)) if (Meter_initFn(this))

View File

@ -25,26 +25,26 @@ void fail() {
} }
void* xMalloc(size_t size) { void* xMalloc(size_t size) {
assert(size > 0);
void* data = malloc(size); void* data = malloc(size);
if (!data && size > 0) { if (!data) {
fail(); fail();
} }
return data; return data;
} }
void* xCalloc(size_t nmemb, size_t size) { void* xCalloc(size_t nmemb, size_t size) {
assert(nmemb > 0);
assert(size > 0);
void* data = calloc(nmemb, size); void* data = calloc(nmemb, size);
if (!data && nmemb > 0 && size > 0) { if (!data) {
fail(); fail();
} }
return data; return data;
} }
void* xRealloc(void* ptr, size_t size) { void* xRealloc(void* ptr, size_t size) {
if (!size) { assert(size > 0);
free(ptr);
return NULL;
}
void* data = realloc(ptr, size); // deepcode ignore MemoryLeakOnRealloc: this goes to fail() void* data = realloc(ptr, size); // deepcode ignore MemoryLeakOnRealloc: this goes to fail()
if (!data) { if (!data) {
free(ptr); free(ptr);