Skip to content
/ salloc Public

It is a new function in c that let you use allocate memory: specifing the number of bytes allocated.

License

Notifications You must be signed in to change notification settings

sialpi/salloc

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

salloc – Simple Memory Allocator using brk

salloc is a minimal implementation of malloc written in x86-64 assembly (GAS), using the Linux brk syscall to allocate dynamic memory in C programs. This project is intended for learning how heap memory works at a low level and understanding memory allocation without relying on the standard C library.


Features

  • Dynamic memory allocation using the program break.
  • Returns a valid pointer to allocated memory.
  • Minimal: does not support free or advanced block management.
  • Implemented in x86-64 GAS assembly.
  • Easy to integrate with C programs.

How it Works

  1. Reads the current program break with brk(NULL)old_break.

  2. Adds the requested sizenew_break.

  3. Calls brk(new_break):

    • If the kernel allows it, the break moves → memory allocated.
    • If it fails, returns NULL.
  4. Returns old_break as a pointer to the newly allocated memory.

Note: Memory pages may not be physically mapped until accessed (lazy allocation).


Function Prototype

void* salloc(size_t size);
  • size – the number of bytes to allocate.
  • Returns a pointer to the allocated memory or NULL on failure.

Example Usage in C

#include <stdio.h>
#include <stdint.h>

void* salloc(size_t size); // assembly function declaration

int main()
{
    char* p = (char*)salloc(100);  // allocate 100 bytes
    if (!p)
    {
        printf("Allocation failed!\n");
        return 1;
    }

    for (int i = 0; i < 100; i++)
        p[i] = (char)(i % 256);

    for (int i = 0; i < 10; i++)
        printf("%d ", (unsigned char)p[i]);
    printf("\n");

    return 0;
}

Compilation

  1. Assemble the .s file:
gcc -c salloc.s -o salloc.o -no-pie
  1. Compile the C file and link:
gcc -no-pie test.c salloc.o -o test
  1. Run:
./test

-no-pie is required because we are working with direct linear addresses of the heap.


Technical Notes

  • Target architecture: x86-64 Linux (System V ABI)

  • Arguments are passed in registers:

    • %rdi – first argument (size)
    • %rsi, %rdx – used internally
  • Return value:

    • %rax – pointer to allocated memory or NULL if allocation fails
  • Does not manage memory blocks; multiple calls simply move the program break forward.

About

It is a new function in c that let you use allocate memory: specifing the number of bytes allocated.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published