C Program To Investigate Memory Sections

The program below illustrates functions and methods you can use to investigate the allocated (virtual) memory of your process. For instance, you can get and print the limit of your data section, guess the limit of your stack and so on.

One curious thing you’ll notice is that small mallocs appear to allocate memory inside the heap as expected (sbrk(0) will return the top of the heap). But you request a larger memory section from malloc it will actually not use the heap and instead use an mmap() system call to map a file to memory. You can read more about this on the StackOverflow thread I started.

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

int globalVar;

int main(){
        int localVar;
        int *ptr;

        printf("localVar address (i.e., stack) = %p\n",&localVar);
        printf("globalVar address (i.e., data section) = %p\n",&globalVar);
        printf("Limit of data section = %p\n",sbrk(0));

        ptr = malloc(sizeof(int)*1000);

        printf("ptr address (should be on stack)= %p\n",&ptr);
        printf("ptr points to: %p\n",ptr);
        printf("Limit of data section after malloc= %p\n",sbrk(0));

        return 0;

Leave a Reply

Your email address will not be published. Required fields are marked *