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.
#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();
}
[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) dump memory ~/dump2.hex 0x7fff98513148 0x7fff98513150
[josh@TestBox ~]$ xxd dump2.hex
0000000: 6b03 0000 0901 0000 k.......
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With