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

ぃ、小莉子 提交于 2020-01-03 00:41:34

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/28107665/is-the-memory-address-returned-by-malloc-always-interchangeable-by-a-pointer-to

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!