Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to view binary content of a C++ integer in gdb?

Tags:

c++

gdb

int main()
{
     int a = 0;
}

I compile: g++ -std=c++14 -g test.cpp

Run program in gdb:

gdb ./a.out

(gdb) break main

(gdb) run

(gdb) next

What I have tried:

(gdb) print /t &a

That prints 11111111111111111111111111111111101110101111100

That doesn't look like the right number, I was expecting 0000....0000. How can I print binary values from the memory location of the integer variable a ?

like image 320
Robert C. Holland Avatar asked Dec 10 '22 10:12

Robert C. Holland


2 Answers

You are trying to print the address of a which is in the stack frame of main and has nothing to do with its value. Try:

print /t a

like image 101
Yuval Ben-Arie Avatar answered Dec 30 '22 06:12

Yuval Ben-Arie


Use p /x to print something in hex. Let us look after a has been set to 0.

(gdb) n
28               return(0);
(gdb) p a
$6 = 0

ok

(gdb) p /x a
$7 = 0x0

ok in hex

(gdb) p /x &a
$8 = 0x7fffffffe3dc

address of a in automatic memory (on the stack).

(gdb) p /t &a
$9 = 11111111111111111111111111111111110001111011100

looks like binary, and slightly different on my machine than yours. good.

(gdb) print /t &a

That prints 11111111111111111111111111111111101110101111100

That doesn't look like the right number?

33 1's at the front, and the last 4 bits are 0xc.

Mine looks correct compared to hex. 0x7fffffffe3dc.

I suspect yours is too.

If you were expecting a bunch of 0's. that would be the value of a, not the address of a

(gdb) p /t a
$10 = 0

gdb shrunk the results - 0 is indeed a bunch of 0's.

like image 20
2785528 Avatar answered Dec 30 '22 06:12

2785528