• Uncategorized

About c : How-do-you-allocate-memory-on-the-heap-without-using-libc-in-linux-duplicate

Question Detail

I’m trying to alocate memory on the heap without using libc and using linux system calls. I’ve tried using mmap and brk but brk doesn’t return the end of heap like I’ve read it does for most systems, sbrk won’t work because it doesn’t exist as a syscall, and mmap just causes a segfault.


#define PROT_READ 0x1
#define PROT_WRITE 0x2
#define MAP_PRIVATE 0x2
#define MAP_ANONYMOUS 0x20

extern void *mmap(void *addr, unsigned long sz, int prot, int mode, int fd, unsigned long offset);
extern void  exit(int exit_code);

int _start()
    void *mem = mmap(0, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

    *(int*)mem = 4;


The reason I am trying to do this is because I am working on a replacement libc (obviously not a competent one if I don’t know how to do this, it’s mainly a learning exercise/fun project) and I need to figure out how to actually allocate on the heap. I’ve looked for a while but I still have no clue how it works.


    .global mmap
    mov $9, %rax

    .global exit
    mov $60, %rax

The compile command I’m using is gcc -nostdlib _start.c syscalls.s.

Like I said, I am running Linux. Specifically: Ubuntu 20.04 LTS with kernel 5.11.0-43-generic.

Question Answer

You may also like...

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.