c - malloc 是否负责内存对齐?

标签 c malloc system-calls

我使用 malloc 分配了 5 个字节的内存,并且能够使用这 5 个字节来存储字符或整数。 例如,使用第一个字节存储字符,接下来的四个字节存储整数。 malloc 如何处理内存对齐问题?

最佳答案

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/

相关文章:

c++ - 魔术 COLORREF/RGB 值确定何时使用亮/暗文本

c++ - 额外的函数/方法定义会增加程序的内存占用吗?

c - 使用 Malloc (char & int) 分配内存

Linux API : is it possible to specify `O_SYNC` option for a single `write` syscall

c - 我怎样才能以这种方式拆分这个链表

c - 在 C 语言中从文件中读取整数时遇到问题

c - 如何为结构中的 int 数组分配内存

c++ - 如何在多线程中关闭 malloc() 的 mmap 使用?

linux - 如何让Linux上的 `write()`系统调用立即生效?

c - vfork() 系统调用中的返回值