mem.c

DownloadView Raw

/**
 * mem.c
 *
 * Inspecting memory addresses to learn the locations of the stack, heap, code,
 * and more.
 *
 * Compile: gcc -g -Wall mem.c -o mem
 * Run: ./mem
 *
 * Sample output:
 * Address of uninitialized data = 0x11034
 * Address of initialized data   = 0x8538
 * Address of code               = 0x8441
 * Address of a (stack)          = 0xbe96d3f8
 * Address of b (stack)          = 0xbe96d3fc
 * Address of c (heap)           = 0x12008
 * Address of d (heap)           = 0x12018
 */

#include <stdio.h>
#include <stdlib.h>

/* Uninitialized data: */
int global;

/* Initialized data (string literal, in this case) */
char *literal = "Hello world!";

/* main() will be the first address in the code segment */
int main(void) {
    /* a and b are located on the stack: */
    int a = 0;
    int b = 0;

    /* c and d are located on the heap: */
    int *c = malloc(sizeof(int));
    int *d = malloc(sizeof(int));

    printf("Address of uninitialized data = %p\n", &global);
    printf("Address of initialized data   = %p\n", literal);
    printf("Address of code               = %p\n", main);
    printf("Address of a (stack)          = %p\n", &a);
    printf("Address of b (stack)          = %p\n", &b);
    printf("Address of c (heap)           = %p\n", c);
    printf("Address of d (heap)           = %p\n", d);

    /**
     * Which way does the stack grow?
     * Which way does the heap grow?
     *
     * Do you think these addresses are *logical* or *physical*?
     */

    return 0;
}