ZPS
ZPS

Reputation: 1596

Can you fit smaller sized structures into a larger chunk of memory?

I have this structure:

typedef struct
{
int data[10];
} small_structure;

and this code:

small_structure *s_struct;
void * chunk;

chunk = malloc(1000);
s_struct = chunk;

Is it ok to do something like this? Ignore the fact that this is wasting memory.

Upvotes: 0

Views: 80

Answers (3)

Carl Norum
Carl Norum

Reputation: 225052

Yes, that's fine. malloc will return you suitably aligned memory. Just assigning any arbitrary void * pointer to a small_structure * variable is not OK, however. That means your specific example is fine, but something like:

int function(void *p)
{
    small_structure *s = p;
    return s->data[0];
}

is not! If p isn't suitably aligned for a small_structure * pointer, you've just caused undefined behaviour.

Upvotes: 2

Rudy Velthuis
Rudy Velthuis

Reputation: 28826

AFAICT, there is nothing wrong with it (except for the waste ;-).

Note that you'll have to fill the struct with useful data before you use it.

Upvotes: 2

Gabe
Gabe

Reputation: 86768

Yes, it is always legal to allocate more memory than you need, so long as that much memory is available.

Upvotes: 4

Related Questions