This library provides a simple mechanism to manage dynamic memory allocations in C and to ensure that all allocated memory is freed at the end of the program, preventing memory leaks. It includes functions for allocating and freeing memory, and maintains a list of all allocated addresses.
Allocates, reallocates, or frees memory based on the specified operation.
-
Parameters:
size: The size of the memory to allocate.ptr: The pointer to the memory to reallocate or free. Set toNULLfor new allocations.mode: The operation to perform. This can be:MALLOCformallocCALLOCforcallocFREE_PTRto free a specific pointerFREE_ALLto free all allocated memory
-
Returns: A pointer to the allocated memory, or
NULLif an error occurs.
-
clone the repo inside your main project:
git clone git@github.com:nourddine-benyahya/ft_alloc.git -
append this inside your makefile in building target rule
make -C ft_alloc all -
append this inside your makefile in librarys includes
alloc/ft_alloc.a -
include
#include "ft_alloc.h"in your header file#include "ft_alloc.h"
before :
LIBS = libft/libft.a
$(NAME) : $(OBJ)
$(CC) $(CFLAGS) $(OBJ) $(LIBS) -o $(NAME)
after :
LIBS = libft/libft.a alloc/ft_alloc.a
$(NAME) : $(OBJ)
make -C ft_alloc all
$(CC) $(CFLAGS) $(OBJ) $(LIBS) -o $(NAME)
make the libarary
cd ft_alloc
#include "ft_alloc.h"
void leaks(void)
{
system("leaks a.out");
}
int ft_testing(void)
{
//check memory leaks at the exit of the programm
atexit(leaks);
// Allocate memory using malloc
void *ptr1 = ft_alloc(sizeof(char *), NULL, MALLOC);
// Allocate memory using calloc
void *ptr2 = ft_alloc(sizeof(int *), NULL, CALLOC);
// Free a specific pointer
ft_alloc(0, ptr1, FREE_PTR);
// Free all allocated memory
ft_alloc(0, NULL, FREE_ALL);
return (0);
}
int main()
{
ft_testing();
}