True memory locations of C variables
Asked Answered
S

1

7

In an effort to learn more about C, I have been playing with it for the past 2 days. I wanted to start looking at how C is structured during runtime so, I built a crappy program that asks a user for two integer values, then prints the memory location of the integer variables. I then want to verify that the data is actually there so, I have the program suspended with getchar() in order to open up GDB and mine the memory segment to verify the data but, the data at those locations is not making much sense to me. Can someone please explain what is going on here.

Program Code:

#include <stdio.h>

void pause();

int main() {
   int a, b;
   printf("Please enter number one:");
   scanf("%d", &a);
   printf("Please enter number two:");
   scanf("%d", &b);
   printf("number one is %d, number two is %d\n", a, b);
  // find the memory location of vairables:
   printf("Address of 'a' %pn\n", &a);
   printf("Address of 'b' %pn\n", &b);
   pause();
}

void pause() {
   printf("Please hit enter to continue...\n");
   getchar();
   getchar();
}

Output:

[josh@TestBox c_code]$ ./memory 
Please enter number one:265
Please enter number two:875
number one is 265, number two is 875
Address of 'a' 0x7fff9851314cn
Address of 'b' 0x7fff98513148n
Please hit enter to continue...

GDB Hex dump of memory Segments:

(gdb) dump memory ~/dump2.hex 0x7fff98513148 0x7fff98513150

[josh@TestBox ~]$ xxd dump2.hex 
0000000: 6b03 0000 0901 0000                      k.......
Subak answered 6/6, 2017 at 15:18 Comment(1)
Tip: If one views data in hexadecimal with GDB, might as well input the data as hexadecimal. scanf("%X", &a); and Please enter number one:456789ABDetrusion
P
9

6b030000 and 09010000 are little-endian (least significant byte first). To read them in a more natural fashion, reverse the order of the bytes:

6b030000 => 0000036b => 875 in decimal

09010000 => 00000109 => 265 in decimal

Pronunciation answered 6/6, 2017 at 15:22 Comment(1)
Yeah... I should have know that. Now I feel dumb. Thank you very much!Subak

© 2022 - 2024 — McMap. All rights reserved.