P Krishnama Naidu
P Krishnama Naidu

Reputation: 45

"Cannot access memory at address 0x600b0c" & "No symbol "n" in current context." in case of global & local variable when compiling with gdb

I searched for solution in Internet and found some results but still getting the error. I have a local variable n and global variable undefined in my C program. And Error or bug I got :

    print f("Enter value m & n : ");
    (gdb) set variable n = 2
     No symbol "n" in current context.
    (gdb) set variable m = 2
    Cannot access memory at address 0x600b0c

Upvotes: 0

Views: 887

Answers (1)

Rupert Swarbrick
Rupert Swarbrick

Reputation: 2803

This would be easier to tell if you'd posted some code, but let's suppose that it looks something like this:

int m;

int read_nums (void)
{
    printf ("Enter value of m and n: ");
    int n = scanf ("%d");
    m = scanf ("%d");
    return n + m;
}

Your GDB instance is sitting on the first line, so n is not currently in scope. With an optimising compiler, that is still true if your code looks like this:

int m;
int read_nums (void)
{
    int n;
    printf ("Enter value of m and n: ");
    n = scanf ("%d");
    m = scanf ("%d");
    return n + m;
}

The compiler transforms the program to minimise the scope of variables quite early in the compilation process.

If you're trying to set the value of n with GDB, it's possible that the variable becomes live after the scanf line. In that case, use GDB's next command to step until it has been set and then change it with the set command (or something like p n = 2).

For code as simple as what I wrote, the compiler will completely elide n and it will generate something more like this:

int m;
int read_nums (void)
{
    printf ("Enter value of m and n: ");
    return scanf ("%d") + (m = scanf ("%d"));
}

where n never exists. To set that value after the fact, you'll have to allow whatever value is based on n to be generated and then set that appropriately instead.

If you can easily recompile your code, you might consider compiling it with -O0 -g3 (GCC flags, but reasonably standard) to disable all optimisation while you poke around with the debugger: it's often a lot easier to match up with the C code then. Barring bugs in the compiler, you can get everything working with those flags then switch optimisation back on at the end.

I'm afraid I don't know what's going on with the m error you see. The address looks rather surprising: maybe you need to tell us more about your environment (linux? embedded?) and post some of your code.

Upvotes: 1

Related Questions