Skip to content

Instantly share code, notes, and snippets.

@yetimdasturchi
Created April 2, 2024 23:27
Show Gist options
  • Save yetimdasturchi/e389937dc1e4ff7f4fc1b0b58e9a8586 to your computer and use it in GitHub Desktop.
Save yetimdasturchi/e389937dc1e4ff7f4fc1b0b58e9a8586 to your computer and use it in GitHub Desktop.
Example code for explaining how malloc and free work in C language.
#include <sys/mman.h>
void* c_malloc(size_t size) {
void* ptr;
asm volatile (
"mov $9, %%rax\n"
"mov $0, %%rdi\n"
"mov %1, %%rsi\n"
"mov $3, %%rdx\n"
"mov $34, %%r10\n"
"mov $-1, %%r8\n"
"mov $0, %%r9\n"
"syscall\n"
"mov %%rax, %0\n"
: "=r"(ptr)
: "r"(size)
: "rax", "rdi", "rsi", "rdx", "r10", "r8", "r9"
);
return ptr;
}
void c_free(void* ptr, size_t size) {
asm volatile (
"mov $11, %%rax\n"
"mov %0, %%rdi\n"
"mov %1, %%rsi\n"
"syscall\n"
:
: "r"(ptr), "r"(size)
: "rax", "rdi", "rsi"
);
}
void print_point(void* ptr) {
unsigned long long addr = (unsigned long long)ptr;
char output[16];
int i = 0;
for (int j = 0; j < 16; j++) {
unsigned long long nibble = (addr >> (60 - 4 * j)) & 0xF;
output[i++] = nibble < 10 ? '0' + nibble : 'a' - 10 + nibble;
}
asm volatile (
"mov $1, %%rax\n"
"mov $1, %%rdi\n"
"movq %0, %%rsi\n"
"mov $16, %%rdx\n"
"syscall\n"
:
: "r"(output)
: "rax", "rdi", "rsi", "rdx"
);
}
void print_value(int* ptr) {
int value = *ptr;
char output[16];
int i = 0;
if (value < 0) {
output[i++] = '-';
value = -value;
}
do {
output[i++] = '0' + (value % 10);
value /= 10;
} while (value != 0 && i < 16);
int j = 0;
if (output[0] == '-') j = 1;
while (j < i / 2) {
char temp = output[j];
output[j] = output[i - j - 1];
output[i - j - 1] = temp;
j++;
}
asm volatile (
"mov $1, %%rax\n"
"mov $1, %%rdi\n"
"movq %0, %%rsi\n"
"mov $16, %%rdx\n"
"syscall\n"
:
: "r"(output)
: "rax", "rdi", "rsi", "rdx"
);
}
void print_newline() {
char newline = '\n';
asm volatile (
"mov $1, %%rax\n"
"mov $1, %%rdi\n"
"movq %0, %%rsi\n"
"mov $1, %%rdx\n"
"syscall\n"
:
: "r"(&newline)
: "rax", "rdi", "rsi", "rdx"
);
}
int main() {
// int* ptr = malloc(sizeof(int));
size_t size = sizeof(int);
int* ptr = c_malloc(size);
//if (ptr == NULL)
if (ptr == MAP_FAILED)
return -1;
*ptr = 33;
print_value( ptr );
print_newline();
print_point( ptr );
//free(ptr)
c_free(ptr, size);
//ptr null
asm volatile (
"movq $0, %0\n"
: "=r"(ptr)
:
: "memory"
);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment