excuse my English, I'm actually Spanish. It has been an hour since I'm trying to solve a problem which it seems it has no solutions. I'm trying to implement malloc and free. This is the code which I've written so far:

#define _DEFAULT_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

typedef struct block_on_free {
    int size;
    struct block_on_free *previous;
    struct block_on_free *next;
    void *data;
} block_on_free;

block_on_free *phead = NULL;

size_t icf_malloc (size_t size) {

    for (block_on_free *current = phead; current != NULL; current = current->next) {
        if (current->size >= size) {
            if (current->previous == NULL) 
                phead = current->next;
            else 
                current->previous->next = current->next;
            
            return current;
        }
    }

    // No compatible block on free list
    block_on_free *new = sbrk (size + sizeof (block_on_free));
    new->size = size + sizeof (block_on_free);
    new->next = NULL;
    new->previous = NULL;
    new->data = (void *) (char *) new + sizeof (block_on_free);
    return new->data;
}

Now, I'm trying to implement free, however, I'm wondering how could I deallocate memory from the heap and if someone attempts to tamper with the deallocated block of memory throw a SEGMENTATION FAULT right away as it would happen if we use the free library function

Thank you in advance.

0

There are 0 best solutions below