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.
- Dynamic memory allocation using the program break.
- Returns a valid pointer to allocated memory.
- Minimal: does not support
freeor advanced block management. - Implemented in x86-64 GAS assembly.
- Easy to integrate with C programs.
-
Reads the current program break with
brk(NULL)→old_break. -
Adds the requested size →
new_break. -
Calls
brk(new_break):- If the kernel allows it, the break moves → memory allocated.
- If it fails, returns
NULL.
-
Returns
old_breakas a pointer to the newly allocated memory.
Note: Memory pages may not be physically mapped until accessed (lazy allocation).
void* salloc(size_t size);size– the number of bytes to allocate.- Returns a pointer to the allocated memory or
NULLon failure.
#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;
}- Assemble the
.sfile:
gcc -c salloc.s -o salloc.o -no-pie- Compile the C file and link:
gcc -no-pie test.c salloc.o -o test- Run:
./test
-no-pieis required because we are working with direct linear addresses of the heap.
-
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 orNULLif allocation fails
-
Does not manage memory blocks; multiple calls simply move the program break forward.