Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

True memory locations of C variables

Tags:

c

gdb

hexdump

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.......
like image 589
Joshua Faust Avatar asked Jun 06 '17 15:06

Joshua Faust


People also ask

Where in memory are my variables stored in C?

Variables are usually stored in RAM. This is either on the heap (e.g. all global variables will usually go there) or on the stack (all variables declared within a method/function usually go there). Stack and Heap are both RAM, just different locations. Pointers have different rules.

What is the location of a variable in memory called?

Each memory cell has an address. Python and other high-level languages use a symbol table to map a variable name to the address it represents. The program puts data in contiguous memory. So the variable 'x' is at address 0, 'y' at address 4.


1 Answers

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

like image 160
Dark Falcon Avatar answered Sep 19 '22 01:09

Dark Falcon