c++ - 为什么 Malloc() 关心边界对齐?

标签 c++ c pointers memory-management

我听说 malloc() 根据分配的类型对齐内存。例如,来自Understanding and Using C Pointers一书:

The memory allocated will be aligned according to the pointer's data type. Fore example, a four-byte integer would be allocated on an address boundary evenly divisible by four.

如果我跟随,这意味着 int *integer=malloc(sizeof(int)); 将分配在可被四整除的地址边界上。即使没有在 malloc 上强制转换 (int *)

我在一个聊天服务器上工作;我读到了 similar effectstructs.

我不得不问:从逻辑上讲,为什么地址边界本身在什么上可分很重要?使用地址 129 上的整数分配一组内存到 n*sizeof(int) 有什么问题?

我知道指针算术是如何工作的*(integer+1),但我不知道边界的重要性...

最佳答案

The memory allocated will be aligned according to the pointer's data type.

如果你在谈论 malloc,这是错误的。 malloc 不关心您如何处理数据,它会分配内存以适应最严格的 native 实现类型。

来自标准:

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)

还有:

Logically, why does it matter what the address boundary itself is divisible on

由于底层机器的工作原理,访问未对齐的数据可能更昂贵(例如 x86)或非法(例如 arm)。这让硬件可以走捷径,提高性能/简化实现。

关于c++ - 为什么 Malloc() 关心边界对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23575489/

相关文章:

c++ - 如何在 Win32 C++ 中将类型 "int"转换为类型 "LPCSTR"

C++:指向数据成员或特征的指针?

c++ - 在 C/C++ 中将 int* 转换为 int(*)[n]

c - 错误: invalid operands to binary * Pointer to a pointer to a matrix

c - 2个int指针之间的指针差异

C:指向结构定义中结构的指针

c# - 在 C# 应用程序退出时清理非托管 C++ 线程

c++ - 在本地修改的按值传递的参数会发生什么情况?

c - FreeType 库和 "Undefined reference to FT_Init_FreeType"

c - 非零分母的 EXC_ARITHMETIC 错误 - XCode