Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are best practices for finding a bug in a C program that only shows up in optimized build

Tags:

c

debugging

gdb

My program uses a third part library that throws segmentation fault at some point. I tried to compile the library with debug symbols and without compiler optimization, and the crash gone away. My suspect is that compiler optimizations revealed this bug. What are best practices for debugging cases like this?

EDIT - (corrected the statement above: "revealed" instead of "caused")

I think I was misunderstood. I didn't have an intention to blame compiler, or something like that. I only asked for best practices for finding a bug in such a situation, where I don't have debug symbols in the 3rd party library (the crash backtrace leads to the 3rd party library).

like image 313
Michael Spector Avatar asked Jun 23 '11 14:06

Michael Spector


People also ask

How does compiler optimization work?

Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.


1 Answers

What you describe is quite common. And it's almost never ever a bug in the compiler optimization. Optimization does a lot of things to your code. Variables get reordered/optimized away etc. If you have one buffer overflow, it might just overflow memory that's no big deal in the debug build, but that memory is very important in the optimization build.

Use valgrind to track down memory errors - they're almost always the cause of the symptoms you see.

like image 147
nos Avatar answered Nov 15 '22 13:11

nos