# Imperfect debugging

## Recommended Posts

Hi. I'm using gcc and gdb/ddd. Every once in a while I'll write a program that segfaults, but when run in the debugger it works perfectly. Since debuggers are supposed to not alter the result of a program, what can be going wrong? Sorry to not have much detail, it's happened in various projects. The only common factor seems to be that it happens in libraries (prominent, supposedly stable ones) which don't have debugging symbols. I don't have a clue how debuggers actually work, but I was under the impression that they're passive observers (save perhaps for breakpoints). Does anyone know what the difference is in executing with/without a debugger attatched and how that could interfere?

##### Share on other sites
No experience of gcc/gdb, I use msvc++, but in my experience the debug builds use different memory allocaters, so if you have some obscure over-array-bounds read or write, in the debug build your arbitrary heap pointer may be pointing to memory that has been allocated for your program, ie in the address space of the debugger or such, that coincidentally doesn't crash the debugger. In release, the pointer then ends up pointing to a more dangerous area just because of the way the memory allocation works... However, in this kind of case you at least know that you have a loose pointer somewhere...

##### Share on other sites
There are several differences when you're running a program from a debugger. For instance, the following code segfaults without a debugger but works with one:

int main(){  char *c="Hello";  c[3]="w";}

The reason for this is that the constant region where the literal is stored will be marked as read-only (leading to a segfault when it is modified) but when run from a debugger (which may choose to alter any part of the program on the fly) the constant region is read-write and thus no error happens.

I suspect other similar effects happen.

##### Share on other sites
If you are using Linux I would recommend that you take a look at valgrind, which is a tool that among other things can help you detect memory errors. I usually run it as "valgrind --leak-check=yes ./program" to check for memory leaks and other memory related errors.

Also, make sure that you tell gcc to show all warnings (I usually use -Wall -Werror -pedantic). ToohrVyk's example should for example have emitted a warning about converting from a string literal to char* (actually, it doesn't compile at all for me with gcc 4.3.2, emitting an error on the assignment line even without any flags).

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628282
• Total Posts
2981805

• 9
• 10
• 11
• 17
• 14