malloc 是否负责内存对齐?
Does malloc takes care of memory allignment?
我使用 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.
这是无效的。您需要将 char 和整数捆绑在一个结构中(可能包括填充),或者为它们设置 2 个单独的内存块。或者将它们序列化(这是另一个问题)。
我使用 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.
这是无效的。您需要将 char 和整数捆绑在一个结构中(可能包括填充),或者为它们设置 2 个单独的内存块。或者将它们序列化(这是另一个问题)。