I've heard that malloc()
aligns memory based on the type that is being allocated. For example, from the book Understanding and Using C Pointers:
The memory allocated will be aligned according to the pointer's data type. Fore example, a four-byte integer would be allocated on an address boundary evenly divisible by four.
If I follow, this means that
int *integer=malloc(sizeof(int));
will be allocated on an address boundary evenly divisible by four. Even without casting (int *)
on malloc.
I was working on a chat server; I read of a similar effect with struct
s.
And I have to ask: logically, why does it matter what the address boundary itself is divisible on? What's wrong with allocating a group of memory to the tune of n*sizeof(int)
using an integer on address 129
?
I know how pointer arithmetic works *(integer+1)
, but I can't work out the importance of boundaries...