malloc 返回的内存地址是否总是可以通过指向另一种类型的指针互换?
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);
另一方面:
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);
这个假设是正确的还是我遗漏了什么?
C 标准保证 malloc 将 return 内存适当对齐最严格的 基本类型 (例如 uint64_t
)。如果您有更严格的要求,则必须使用 aligned_alloc
或类似的东西。
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)
关于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.
就对齐而言,您的代码是正确的。我不是特别喜欢指针转换(char *
到 int *
),但我认为它应该可以正常工作。
char arr[512] = {0};
int *ptr = (int *)arr; // WRONG
// A bus error can be caused by unaligned memory access
printf("%d\n", *ptr);
另一方面:
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);
这个假设是正确的还是我遗漏了什么?
C 标准保证 malloc 将 return 内存适当对齐最严格的 基本类型 (例如 uint64_t
)。如果您有更严格的要求,则必须使用 aligned_alloc
或类似的东西。
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)
关于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.
就对齐而言,您的代码是正确的。我不是特别喜欢指针转换(char *
到 int *
),但我认为它应该可以正常工作。