Realloc allocates 16 Bytes of memory when pointer is NULL and size is 0

Yes, malloc(0) often returns a minimum size pointer instead of returning NULL. That is why I don't think of this behavior as a bug.

You may better understand my (initial) surprise if you see my original code:

void MELHashMapBucketListDeinit(MELHashMapBucketList * _Nonnull self) {
    free(self->memory);
    self->memory = NULL;
    self->count = 0;
    self->capacity = 0;
}

Using free, I overlooked the fact that it would instead be calling malloc when self->memory is NULL.

It was easy to fix the leak once I understood what was going on:

if (self->memory != NULL) {
    playdate->system->realloc(self->memory, 0);
    self->memory = NULL;
}

No need to go that far :+1: , I think a simple mention of this behavior in the documentation should be enough.

(And talking about the documentation, playdate->sprite->free is actually called playdate->sprite->freeSprite).

2 Likes