由malloc返回的内存地址是否总是可以由指向另一种类型的指针互换? [英] Is the memory address returned by malloc always interchangeable by a pointer to another type?

查看:50
本文介绍了由malloc返回的内存地址是否总是可以由指向另一种类型的指针互换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

另一方面:

保证malloc给您的块是对齐的,以便它 可以保存任何类型的数据.

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?

推荐答案

C标准保证malloc将为最严格的基本类型(例如uint64_t)返回适当对齐的内存.如果您有更严格的要求,则必须使用aligned_alloc或类似的内容.

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

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);

aligned_alloc函数为其对象分配空间的对象 对齐方式是通过对齐方式指定的,对齐方式的大小是通过尺寸指定的, 且其值不确定.

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 *),但是我认为它应该可以正常工作.


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.

这篇关于由malloc返回的内存地址是否总是可以由指向另一种类型的指针互换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆