我使用 malloc 分配了 5 个字节的内存,并且能够使用这 5 个字节来存储字符或整数。 例如,使用第一个字节存储字符,接下来的四个字节存储整数。 malloc 如何处理内存对齐问题?
最佳答案
If allocation succeeds, returns a pointer to the lowest (first) byte in the allocated memory block that is suitably aligned for any object type.
因此内存块针对任何对象类型都是对齐的。
use the first byte to store a character and the next four bytes to store an integer.
这是无效的。您需要将字符和整数捆绑在一个结构中(可能包括填充),或者为它们提供 2 个单独的内存块。或者序列化它们(这是另一个问题)。
关于c - malloc 是否负责内存对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49433471/