作者StubbornLin (Victor)
看板C_and_CPP
标题[问题] C/C++的new申请出来的记忆体位址保证对齐吗?
时间Tue Feb 3 17:32:55 2009
http://blog.ez2learn.com/2009/02/03/data-alignment/
记忆体位对齐资料的存取会比较快
我记得以前记得好像看到有人的程式申请记忆体时会故意申请大一点的
然後再来进行位址对齐 只用对齐的位址当开头
可是我总觉得我如果是写c++的runtime 像是new我可能在设计时
就让它传回来的位址都是对齐好的
我写了程式下去试
for(size_t i = 0; i < 100; ++i) {
char *p = new char[123];
if(reinterpret_cast<size_t>(p) % 4) {
cout << "*";
system("pause");
}
cout << reinterpret_cast<void *>(p) << endl;
}
for(size_t i = 0; i < 100; ++i) {
short *p = new short[123];
if(reinterpret_cast<size_t>(p) % 4) {
cout << "*";
system("pause");
}
cout << reinterpret_cast<void *>(p) << endl;
}
for(size_t i = 0; i < 100; ++i) {
float *p = new float[123];
if(reinterpret_cast<size_t>(p) % 4) {
cout << "*";
system("pause");
}
cout << reinterpret_cast<void *>(p) << endl;
}
system("pause");
我发现的确new出来都是对齐好的
但是我不敢确定 所以想请问一下
c++的new有保证对齐吗? 我用的是Visual C++ Express 2008
还是虽然没规定 但它的runtime实作保证对齐?
以上 谢谢
--
哇咧咧 创意投票系统
http://walele.com
易记学 程式设计教学
http://ez2learn.com/
易记学 程式设计讨论区
http://forum.ez2learn.com
VICTOR's 个人Blog
http://blog.ez2learn.com/
财报分析王
http://victorlin.serveftp.org/stock/
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 59.113.156.83
1F:推 yoco315:完全看实做品高兴… 02/03 20:46
2F:→ yoco315:Digital Mars 的 C++ compiler 还可以用参数指定要多少 02/03 20:47
3F:推 yoco315:简单的解法是:不要写出依赖这种东西的 code 02/03 20:49
4F:推 tinlans:new 底层大都是 call C++ std lib,所以 lib 怎麽写就是 02/03 20:51
5F:→ tinlans:怎样,基本上写 lib 的人会考虑机器有没有支援没对齐的指 02/03 20:51
7F:→ tinlans:令,如果机器本身没支援的话通常就是会对齐。 02/03 20:52
8F:→ tinlans:CPU 支援,插的卡不支援,那结果还是要自己搞对齐就是。 02/03 20:52
9F:→ layan:若你用VC Compiler, try _aligned_malloc 02/03 21:58
11F:→ StubbornLin:可是stackoverflow有人回答标准有规定耶 囧 02/03 22:18
12F:→ tinlans:标准是说要能转成任何 type 的 pointer,像是 char * 转 02/04 23:03
13F:→ tinlans:int * 要可以转,有些机器要求 word 定址对齐 32-bit 边界 02/04 23:03
14F:→ tinlans:,要是 char * 是 0x70000001,转 int * 就会有问题。 02/04 23:04
15F:→ tinlans:compiler 只能生出很多指令来达成相同目的,但你 runtime 02/04 23:05
16F:→ tinlans:得来的 pointer value,compiler 无法预测,故有此标准。 02/04 23:05