Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Malloc and alignment

As far as I know, every type – like int – can only be stored at memory addresses which start at a power of 2. Now my question is, how can malloc cope with this requirement? For instance, if I call

void * ptr;
ptr = malloc(8);

Then it is not obvious what I want to store in the given memory block of eight bytes. Is it therefore true that malloc always returns a starting address of the block which is located the largest power of 2 such that every standard type could be stored? If I misunderstand something, please feel free to correct me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

C 2018 7.22.3 specifies the behavior of the memory allocation routines and its paragraph 1 says “… The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement…”

6.2.8 2 says:

… The alignment requirements of the following types shall be fundamental alignments:

  • all atomic, qualified or unqualified basic types;

  • all atomic, qualified or unqualified enumerated types;

  • all atomic, qualified or unqualified pointer types;

  • all array types whose element type has a fundamental alignment requirement;

  • all types specified in Clause 7 as complete object types;

  • all structure or union types all of whose elements have types with fundamental alignment requirements and none of whose elements have an alignment specifier specifying an alignment that is not a fundamental alignment.

6.2.5 14 says:

The type char, the signed and unsigned integer types, and the floating types are collectively called the basic types.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading