我听说 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 effect用 struct
s.
我不得不问:从逻辑上讲,为什么地址边界本身在什么上可分很重要?使用地址 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/