Sign in to follow this  

Imperfect debugging

This topic is 3355 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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).

Share this post


Link to post
Share on other sites
Sign in to follow this