I have a basic C program like this:
#include <stdio.h>
int main()
{
int cookie;
char buf[80];
printf("A: %x B: %x\n", &buf, &cookie);
gets(buf);
if (cookie == 0x11111111){
printf("You win!\n");
} else {
printf("THIS Didn't WORK");
}
}
When I run it, the print statement prints A: efbffab0 B: efbffb08
Yet, if I were to open up this program in gdb and explore the memory address of any of the variables, I get a longer value then what the C program prints out:
Thread 2 hit Breakpoint 1, main () at challenge.c:10
10 if (cookie == 0x41424344){
(gdb) x/50x &buf
0x7ffeefbffab0: 0x41424344 0x41424344 0x41424344 0x41424344
0x7ffeefbffac0: 0x41424344 0x41424344 0x41424344 0x41424344
0x7ffeefbffad0: 0x41424344 0x41424344 0x41424344 0x41424344
0x7ffeefbffae0: 0x41424344 0x41424344 0x41424344 0x41424344
0x7ffeefbffaf0: 0x41424344 0x41424344 0x41424344 0x41424344
0x7ffeefbffb00: 0x41424344 0x00007f00 0x00011025 0x00000000
0x7ffeefbffb10: 0xefbffb28 0x00007ffe 0x20545f3d 0x00007fff
0x7ffeefbffb20: 0x20545f3d 0x00007fff 0x00000000 0x00000000
0x7ffeefbffb30: 0x00000001 0x00000000 0xefbffcb0 0x00007ffe
0x7ffeefbffb40: 0x00000000 0x00000000 0xefbffd09 0x00007ffe
0x7ffeefbffb50: 0xefbffd4b 0x00007ffe 0xefbffd65 0x00007ffe
0x7ffeefbffb60: 0xefbffd74 0x00007ffe 0xefbffd85 0x00007ffe
0x7ffeefbffb70: 0xefbffdce 0x00007ffe
How come the address from my C program, 0xefbffab0
doesn't match the address gdb gives me, 0x7ffeefbffab0
?
Where does the 0x7ffe
prefix come from?
CodePudding user response:
You're using the wrong format specifier for printing a pointer. The x
specifier is for unsigned int
, which on your system is 32 bits, and thus prints only part of the address (however this is just a coincidence, using the wrong format specifier is undefined behavior). The one you want is p
, which is for void *
:
printf("A: %p B: %p\n", &buf, &cookie);