自动存储时长的具体要求是什么?
根据编译器的不同,以下代码:
int main()
{
srand( 0 );
if( rand() ) {
char buffer[600 * 1024] = {};
printf( buffer );
} else {
char buffer[500 * 1024] = {};
printf( buffer );
}
return 0;
}
在最大堆栈大小等于 1 MB 的系统上运行时,要么打印空字符串,要么因堆栈溢出而崩溃。
差异是因为不同的编译器分配自动存储的方式不同。大多数编译器为函数启动时的所有对象分配存储,因此在上面的代码中它们分配 600+400=1100 KB,导致堆栈溢出。一些编译器更聪明,他们发现这两个数组永远无法同时访问,因此他们重用相同的内存,只分配 600 KB,程序运行良好。
现在,标准说 (3.7/1) 存储持续时间定义了存储的最小潜在生命周期,然后 (3.7.2/1) 这些对象的存储[具有自动持续时间]持续到创建它们的块存在为止。
我不明白 3.7/1 和 3.7.2/1 如何一起应用。一种说法是持续时间是最小潜力,另一种则明确表示持续时间直到区块存在。根据第一个,看起来两种分配策略都是合法的,但第二个要求仅使用“重用”分配策略。
3.7/1 和 3.7.2/1 如何共存?在最坏的情况下(第一种策略)分配比程序需要更多的内存是否合法?
Depending on the compiler the following code:
int main()
{
srand( 0 );
if( rand() ) {
char buffer[600 * 1024] = {};
printf( buffer );
} else {
char buffer[500 * 1024] = {};
printf( buffer );
}
return 0;
}
when ran on a system with maximum stack size equal to 1 megabyte either prints an empty string or crashes with a stack overflow.
The difference is because different compilers allocate automatic storage differently. Most compilers allocate storage for all objects on function start, so in the code above they allocate 600+400=1100 kilobytes and that leads to stack overflow. Some compilers are smarter and they see that those two arrays can never be accessible at the same time so they reuse the same memory and only allocate 600 kilobytes and the program runs fine.
Now The Standard says (3.7/1) that storage duration defines the minimum potential lifetime of the storage and then (3.7.2/1) that the storage for these objects [with automatic duration] lasts until the block in which they are created exists.
I don't understand how 3.7/1 and 3.7.2/1 are to be applied together. One says that duration is minimum potential and the other says explicitly that it lasts until the block exists. Looks like according to the first both allocation strategies are legal, but the second demands that only "reuse" allocation strategy is used.
How do 3.7/1 and 3.7.2/1 co-exist? Is it legal to allocate more memory than the program needs in the worst case (the first strategy)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将 3.7/ 作为不同存储类(自动、静态、动态)的介绍性描述和定义来阅读,而不是作为每个存储类的实现要求......然后在 3.7.2/1 中描述了automatich 的实现要求。
阅读 3.7.2/1 并不禁止它存在的时间比块存在的时间长(这只是最小值) - 恕我直言,这是编译器实现者关于可能的优化的一个机会......
I read 3.7/ as an introductory description and definition of the different storage classe (automatic, static, dynamic) and not as the implementation requirement for each... the implementation requirement for automatich is then described in 3.7.2/1 .
Reading 3.7.2/1 it does not forbid that it exists longer than the block exists (that is just the minimum) - IMHO this is an opening for compiler implementors regarding possible optimizations...
“持续到”也是最低要求。
"Lasts until" also is a minimum.