Intel® C++ Compiler
Community support and assistance for creating C++ code that runs on platforms based on Intel® processors.
7956 Discussions

Hard to debug: different behavior of debug and optimized code

dpeterc
Beginner
338 Views
I have recently been a victim of a small memory overwrite bug.
Program ran correctly if compiled with debugging, and crashed
if optimized. Valgrind (memory checking tool) did not report anything useful.

After some good old printf based debugging, I found the small memory overwrite.
Here a small sample code for this kind of problems:
#include 
int main(int argc, char *argv[])
{
int shortArray[5];
int i;

for (i=0; i<6; i++)
shortArray=665;
if (i>6)
printf("I will go beserk with %d ", i);
else
printf("I will survive with %d ", i);
return(0);
}

If you compile it with -g, it manifests the bug, if it is optimized,
it runs correctly.
My real world case was just the other way around, but you get the idea.
Most memory checking debuggin tools do not report bugs on
small overwrites, which still fall into your own memory pool.
So it is extremely difficult to debug this kind of errors in
larger applications, if you can't use the debugger.
Wouldn't it be possible to enforce equal stack memory layout
behavior for optimized program and for debug version?
So at least you get the crash or correct behavior on both
debug and optimized version?

Or if somebody has better ideas how to approach this kind of
bugs, I would like to hear the suggestions.

Duan Peterc
http://www.arahne.si





0 Kudos
1 Reply
TimP
Honored Contributor III
338 Views
A more commonly asked question is how to preserve some debugging capability with partial optimization. Apparently, you don't want interprocedural optimization, so you can set -fno-inline-functions and also set -g along with your optimization switches.
0 Kudos
Reply