[英]Why does g++ make my code execute in a different order than written and how do I disable this “optimization”?
For example: 例如:
#include <stdio.h>
#include <string>
int main() {
std::string* stuff(NULL);
printf("allocating memory..."); //line 2
stuff = new std::string[500000000]; //line 3
delete [] stuff; //line 4
return 0;
}
when executed runs line 3 (and possibly line 4) before line 2. Now I know this is probably some good optimization feature but sometimes the right order is needed. 当执行时,在第2行之前运行第3行(可能还有第4行)。现在我知道这可能是一些不错的优化功能,但有时需要正确的顺序。
The problem is here: 问题在这里:
printf("allocating memory..."); //line 2
In many architectures you have buffered output, which means that what you print on the screen is not shown immediately but stored in a memory buffer. 在许多体系结构中,您已经缓冲了输出,这意味着您在屏幕上打印的内容不会立即显示,而是存储在内存缓冲区中。 To flush the buffer and ensure that he is printed immediately, you can use 要刷新缓冲区并确保立即打印,可以使用
printf("allocating memory...\n"); //line 2 with the \n character that flushes the buffer
although I didn't find anything to prove this besides personal experience, or alternatively, if you don't want to go to a new line (and be absolutely sure of flushing) you can use fflush(stdout)
right after line 2. 尽管除了亲身经历外,我没有发现任何东西可以证明这一点,或者,如果您不想转到新行(并且绝对要刷新),则可以在第二行之后立即使用fflush(stdout)
。
-O0 flag disables all optimizations in GCC. -O0标志禁用GCC中的所有优化。
But the effect you are observing is most probably not due to an optimization but rather a result of file IO buffering. 但是,您观察到的效果很可能不是由于优化,而是文件IO缓冲的结果。
Inserting fflush(stdout) just after printf(...) will make IO system flush the buffer which in case of logging to a file should give you the right order of events (assuming you are logging malloc() calls to the same file and this is where you observe out of order events). 在printf(...)之后插入fflush(stdout)将使IO系统刷新缓冲区,这在登录到文件的情况下应该为您提供正确的事件顺序(假设您正在将malloc()调用记录到同一文件,并且这是您观察故障事件的地方)。
In C++, you might want to write it like this: 在C ++中,您可能要这样写:
#include <iostream>
#include <string>
int main() {
std::string* stuff(NULL);
std::cout << "allocating memory..."; //line 2
std::cout.flush(); // ensures the buffer is actually written to the terminal right here
stuff = new std::string[500000000]; //line 3
delete [] stuff; //line 4
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.