andandandand
andandandand

Reputation: 22270

Understanding this erratic behavior in gdb

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.

Upvotes: 5

Views: 505

Answers (2)

andandandand
andandandand

Reputation: 22270

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.

Upvotes: 1

pm100
pm100

Reputation: 50180

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

Upvotes: 9

Related Questions