Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GDB: How to identify the line number of variable declaration of a specific variable for the current function in gdb

Tags:

c

gdb

How can I identify the line number of variable declaration of a specific variable for the current function in gdb??

Here's a sample code:

1       #include<stdio.h>
2
3       void func(int*);
4
5       void main()
6       {
7       int x;
8       char c[5];
9       int* p;
10      char *g;
11      char *ptr;
12
13      p = &x;
14      g = &c[3];
15      func(&x);
16      ptr = &c[1];
17      c[1]='f';
18      x=12;
19
20      }
21
22      void func(int *l){
23      int x;
24      unsigned int ggg;
25      ggg =100;
26
27      x = 3;
28      *l = x;
29      }
30

Wanted output:
for main()
  variable x, line 7
  variable c, line 8
  variable p, line 9
  variable g, line 10
  variable ptr, line 11

for func()
  variable x, line 23
  variable ggg, line 24

Assuming I'm currently in the main() function. I can get the local variables using "info locals" then parsed its variable names.

(gdb) info locals
x = 4200592
c = "\000ε\030@"
p = 0x7ffd4000
g = 0x40 <Address 0x40 out of bounds>
ptr = 0x13cf304 <Address 0x13cf304 out of bounds>

And using the the list command I was able to get the current scope of the variable but not whole function body. Below is the result of list command, and declaration variable 'x' seems to be missing. I also tried setting the list size to 20, and got the lines starting from 8 to 27, but still not helpful.

(gdb) l
8       char c[5];
9       int* p;
10      char *g;
11      char *ptr;
12
13      p = &x;
14      g = &c[3];
15      func(&x);
16      ptr = &c[1];
17      c[1]='f';

If I check all lines of code in the source code, i might encounter same variable declarations from different functions...help

like image 925
charmae Avatar asked May 15 '12 09:05

charmae


1 Answers

This is easy. You can use list command to find corresponding line.

(gdb) set listsize 1
(gdb) list x
7            int x;
(gdb)

This will show that x is on line 7;

Or use shortcut command l for command list

(gdb) l x
7            int x;
like image 82
user1367893 Avatar answered Oct 11 '22 09:10

user1367893