What the purpose of alignment is and why it is important?

Certain instructions on certain architectures have alignment requirements. If they are not met, the program crashes. Sometimes the program is much slower when data is misaligned.

For instance,

#include <stdlib.h>

int
main()
{
    void *p = malloc(100);
    __float128 *f = p + 8; 
    (*f)++;
}

this program crashes because 128-bit floats must be aligned at multiples of 16, see movdqa.

Now suppose the programmer writes:

struct A {
  __float128 f;
};

and then does:

struct A *a = malloc(sizeof *a);
a->f++;

If malloc() didn't return memory that was 16-byte aligned, then f wouldn't be aligned.

As is, there is an implicit contract between the compiler and malloc(): malloc() guarantees that it returns aligned memory, and the compiler will insert any padding necessary to maintain this alignment.

For instance,

struct B {
    char c;
   // 15 bytes padding
   __float128 f;
};

here, sizeof(struct B) would be 32. If a programmer uses malloc() to allocate an object of type struct B, then the f field inside B will be suitably aligned if and only if the first byte of the allocated memory is.