David Ranieri
David Ranieri

Reputation: 41017

Is the memory address returned by malloc always interchangeable by a pointer to another type?

char arr[512] = {0};
int *ptr = (int *)arr; // WRONG
                       // A bus error can be caused by unaligned memory access

printf("%d\n", *ptr);

On the other hand:

The block that malloc gives you is guaranteed to be aligned so that it can hold any type of data.

char *arr= malloc(512);
int *ptr = (int *)arr; // OK, arr is properly aligned for ptr

memset(arr, 0, 512);
printf("%d\n", *ptr);

Is this assumption correct or am I missing something?

Upvotes: 1

Views: 182

Answers (1)

cnicutar
cnicutar

Reputation: 182619

The C standard guarantees that malloc will return memory suitably aligned for the most stringent fundamental type (for example uint64_t). If you have more stringent requirements you have to use aligned_alloc or something like it.

7.22.3

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 and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated)

About aligned_alloc:

void *aligned_alloc(size_t alignment, size_t size);

The aligned_alloc function allocates space for an object whose alignment is specified by alignment, whose size is specified by size, and whose value is indeterminate.


Your code is correct as far as alignment is concerned. I don't particularly like the pointer conversion (char * to int *) but I think it should work fine.

Upvotes: 3

Related Questions