I have a scenario in which I have to update my server OS version and respectively the g++ version, what I discovered is that the code which was working fine start giving error on the new version (actually segmentation fault). Then debugging through the code, I realized there was something like this:
#include<stdio.h>
int main()
{
char s[8]={'\0'};
sprintf(s,"overflow");
return 1;
}
the compilation was g++ file.cc -O2
Thus the optimization has lead to error as we are assigning the whole character string s, and there is no NULL termination. I just want to ask is it good practice to use optimization flag ON, specially when moving across different version of g++, as the error like above may fall in place due to bad programming practices earlier?
The error is in the code; the fact without the optimization flag you weren’t able to see the error is just bad luck.
Of course optimizers can have bugs, but current gcc produces bad code with
-O2only extremely rarely. There is usually no reason to avoid common optimization flags.This example is more of a reason that you should prefer to compile with a variety of options, preferably with some memory checking options and profilers than it is a reason to avoid optimization.