This repository contains an implementation of malloc() and free() functions in C, which are used to dynamically allocate and free memory at runtime. These functions, MyMalloc() and MyFree(), have been implemented in the file mymalloc.h and mymalloc.c respectively.
To use MyMalloc() and MyFree() functions in your own C program, simply include the mymalloc.h header file in your program and link the mymalloc.c file with your source code at compile time. Here is an example program that uses MyMalloc() and MyFree():#include <stdio.h>
#include <string.h>
#include "mymalloc.h"
int main(int argc, char *argv[]){
int *p1 = (int*)MyMalloc(sizeof(int));
if(p1 == NULL){
printf("Can not allocate memory size %lu \n", sizeof(int));
}
else{
*p1 = 10;
printf("Allocated memory: %d\n", *p1);
}
char *p2 = (char*)MyMalloc(sizeof(char) * 100);
if(p2 == NULL){
printf("Can not allocate memory size %lu \n", sizeof(char) * 100);
}
else{
strcpy(p2, "Allocated memory for 100 characters");
printf("%s\n", p2);
}
MyFree(p1);
MyFree(p2);
return 0;
}
When a memory block is freed, the free() implementation updates the linked list to reflect the freed memory block, and merges adjacent free blocks to reduce fragmentation.
The linked list of free memory blocks is maintained as a global variable, which is not thread-safe.
This implementation of malloc() and free() is not designed to be used in production environments, and is intended only as an educational exercise. There are many more factors to consider in a production-quality memory allocation implementation, such as thread safety, performance, and optimization.