views:

60

answers:

2

Consider the following code:

#include <stdio.h>
#include <ctype.h>

char* Mstrupr(char* szCad); 

int main()
{
    char szCadena[] = "This string should print well.";
    printf("%s\n", Mstrupr(szCadena));
    printf("%s\n", Mstrupr("This string should fail."));
    return 0;
}

char* Mstrupr(char* szCad) 
{
    int i;
    for (i=0; szCad[i]; i++) 
        szCad[i] = toupper(szCad[i]);
    return szCad;
}

The second call to Mstrupr fails to run correctly on linux as its receiving the string as a literal (and not as a char array). When the complete program is run on gdb it fails as well, but when a breakpoint is added to main and the program is run via gdb's next command, the second string is capitalized and printed. Why? I believe this should not be, but my instructor insists that it's part of gdb's design.

+9  A: 

I dont see that its part of gdb's design. It seems like an accidental side effect; gdb made the code segment writable when it set the breakpoint, so your code that overwrites literals there now works

In fact no debugger designer would deliberately make their debugger change the behavior of a program; that makes debugging really hard

pm100
That's probably something that the gdb folks would consider a bug. For most uses (not some embedded ones, though) gdb has to change code to insert a break instruction to implement a break point, which means that it has to change that area of memory to writable. It apparently isn't changing it back to its previous settings.
nategoose
It's really strange, especially since my version of gcc puts everything in a different segment, `.rodata` which gdb has no reason to touch
Hasturkun
+1  A: 

I must point out that I recompiled and re-debugged this code with a newer gdb (GDB 7.1) and this behavior no longer appears. The code appears faulty (Segmentation Fault at the second function call), as it should.

omgzor
sounds like a fixed bug in gdb
pm100
Yes. I believe it is.
omgzor