#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

void display_mem(char* kind) {
    char buf[1024];
    char *ptr, *ptr2;
    ssize_t amount;
    int fd = open("/proc/self/status", O_RDONLY);
    if (fd == -1) {
        printf("cannot open file\n");
        return;
    }
     
    amount = read(fd, buf, 1023);
    buf[amount] = '\0';
    if (!(ptr = strstr(buf, kind))) {
        printf("%s not found in: %s\n", kind, buf);
        close(fd);
        return;
    }

    if (!(ptr2 = strchr(ptr, '\n'))) {
        printf("\\n not found\n");
        close(fd);
        return;
    }

    *(ptr2+1) = '\0';
    printf(ptr);
    close(fd);
}

void* mallocblank(size_t size) {
        void* ptr = malloc(size);
        if (!ptr) {
                return NULL;
        }
        bzero(ptr, size);
        return ptr;
}

#define SIZE 256*1024*1024

int main(int argc, char** argv) {
        void *alloc1, *alloc2, *alloc3;
        
        display_mem("VmRSS");

        alloc1 = mallocblank(SIZE);
        if (!alloc1) {
                printf("malloc failed: %s\n", strerror(errno));
                abort();
        }

        while (1) {
                printf("allocate1\n");
                alloc2 = mallocblank(SIZE);
                if (!alloc2) {
                        printf("malloc failed: %s\n", strerror(errno));
                        abort();
                }
                display_mem("VmRSS");

                printf("allocate2\n");
                alloc3 = mallocblank(SIZE);
                if (!alloc3) {
                        printf("malloc failed: %s\n", strerror(errno));
                        abort();
                }
                display_mem("VmRSS");

                printf("free1\n");
                free(alloc2);
                display_mem("VmRSS");

                printf("free2\n");
                free(alloc3);
                display_mem("VmRSS");
        }
        
        return 0;
}

