When I use realloc in my iOS app, it seems it always increases the memory in my application by a power of 2 instead of what I specify.
This causes some issues when I check the size of the allocation against the size of the objects its storing.
Is this how realloc is designed or is there something I’m doing wrong?
typedef struct {
GLfloat r;
GLfloat g;
GLfloat b;
GLfloat a;
} Color;
typedef struct {
int objectID;
int modelID;
GLfloat scale;
GLfloat translation[3];
GLfloat rotation[3];
Color color;
bool render;
} Object;
Object* objects;
objects = realloc(objects, malloc_size(objects) + sizeof(Object));
NSLog(@"objects size = %lu", malloc_size(objects)); //prints 64 instead of 56
This is an efficiency measure. The arena used by memory allocation routines usually has a fixed “resolution” such as sixteen bytes. That’s because they tend to give you a (for example) sixteen byte header, followed by enough sixteen-byte chunks to satisfy what you need.
That way, it only ever has to allocate sixteen byte chunks from the arena, making splitting and rejoining of those chunks easier (at the minor cost of up to fifteen bytes of wastage per allocation).
But, and this is important, even if you ask for ten bytes and it gives you 1K, you’re still only allowed to use those ten bytes!
If you want to track what you’ve used against what you’ve asked for, that’s an issue you need to handle. Do not rely on information returned from
malloc_sizefor that.