3

Here is a simple program:

#include <stdio.h>
#include <string.h>

typedef struct {
        char str[10];
} my_struct;

static my_struct s1;

int main()
{
        char *temp_str = "test";
        strcpy(s1.str, temp_str);
        printf("%s\n", s1.str);
}

This program compiles and runs as expected, but I am seeing some odd behavior with gdb that I don't quite understand. These gdb commands were run following a breakpoint set on the printf line.

(gdb) p s1.str
$5 = "test\000\000\000\000\000"
(gdb) printf "%s\n", s1.str
test
(gdb) set $tmp = s1
(gdb) printf "%s\n", $tmp.str
Attempt to take address of value not located in memory.

Why does the last command not work? In more complex situations where accessing the variable directly (s1.str) isn't as clean, is there any valid way to use printf with something like $tmp in this example? This is with gdb 7.2.

The following does work however:

(gdb) set $tmp_str = s1.str
(gdb) printf "%s\n", $tmp_str
test

One other point of interest is that if I add an int to the struct (in this case, x - set to 4), I can successfully do:

(gdb) set $tmp = s1
(gdb) printf "%d\n", $tmp.x
4
1
  • For what it's worth, this works fine on gdb-7.6.1. Both printf "%s\n", $tmp.str and printf "%s\n", $tmp->str outputs "test" Commented Oct 25, 2013 at 22:12

1 Answer 1

2

Probably because $tmp points to a structure (s1), not the char array (s1.str), gdb is pretty smart about things, but is usually going to take things literally.

set $tmp = s1

generally means:

set $tmp = (address of)s1

Thus $tmp is only a pointer, technically, you'd have to convert/coerce $tmp to a (struct my_struct) type pointer, from which you could reference the struct contents, str.

set $tmp = (struct my_struct)s1

But I don't think that'll work in gdb (don't know for sure, try it!). In any case:

set $tmp = s1.str
printf "%s\n", $tmp

would likely work for you though.

Sign up to request clarification or add additional context in comments.

1 Comment

I mentioned in the question that the last thing you suggested does work. Also, casting it to my_struct (no need for the extra 'struct' in front of the type) did not help. Still hoping for an answer, but if "nos" is correct with his comment above, this might just be a bug in my (somewhat old) version of gdb.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.