Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8935813
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T10:04:43+00:00 2026-06-15T10:04:43+00:00

I’m writing my own memory allocation program (without using malloc) and now I’m stuck

  • 0

I’m writing my own memory allocation program (without using malloc) and now I’m stuck with the free function (asfree in my code). I believe the functionality for the allocation is all there, the only problem lays on the free function. So by running the code below I can allocate 32 blocks: each block has a size of 48 + 16 (size of header).
So how can I deallocate/free all of them just after I have allocated them? Could you have a look at my free function and point me at the right direction?

P.S.: This is for learning purposes. I’m trying to get my head around structs, linked lists, memory allocations.
Thanks in advance.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BUFFER_SIZE 2048

typedef struct blk_struct
{
    size_t  size_blk;
    struct  blk_struct *next;
    char    data[0];
}blk_struct;

struct blk_struct *first = NULL;
static char buffer[BUFFER_SIZE];

void *asalloc(size_t size)
{
    int nunits = (size + sizeof(blk_struct));
    static int val = 1;

    blk_struct *block, *current;

    //locate position for block
    if(first == NULL)
    {
        block = (blk_struct *)&buffer[0];

        // Sanity check size.
        if(nunits > BUFFER_SIZE)
            return NULL;

        // Initialise structure contents.
        block->size_blk = size;
        block->next     = NULL;

        // Add to linked list.
        first = block;

        // Give user their pointer.
        return block->data;
    }
    //create a free list and search for a free block
    for(current = first; current != NULL; current = current->next)
    {
        // If this element is the last element.
        if(current->next == NULL)
        {
            block = (blk_struct *) (current->data + current->size_blk);

            // Check we have space left to do this allocation
             if((blk_struct *) &block->data[size] >
                     (blk_struct *) &buffer[BUFFER_SIZE])
             {
                 printf("No more space\n");
                 return NULL;
             }

            // Initialise structure contents.
            block->size_blk = size;
            block->next     = NULL;

            // Add to linked list.
            current->next   = block;
            // Give user their pointer.
            return block->data;
        }
    }
    printf("List Error\n");
    return NULL;
}

// 'Free' function. blk_ptr = pointer to the block of memory to be released
void asfree(void *blk_ptr)
{
    struct blk_struct *ptr = first;
    struct blk_struct *tmp = NULL;

    while(ptr != NULL)
    {
        if(ptr == blk_ptr)
        {
            printf("Found your block\n");
            free(blk_ptr);
            break;
        }
        tmp = ptr;
        ptr = ptr->next;
    }
}

// Requests fixed size pointers
int test_asalloc(void)
{
    void *ptr = NULL;
    int size = 48;
    int i = 1;
    int total = 0;

    do
    {
        ptr = asalloc(size);

        if(ptr != NULL)
        {
            memset(ptr, 0xff, size);
            printf("Pointer %d = %p%s", i, ptr, (i % 4 != 0) ? ", " : "\n");
            // each header needs 16 bytes: (sizeof(blk_struct))
            total += (size + sizeof(blk_struct));
            i++;
        }
        asfree(ptr); // *** <--- Calls the 'free' function ***
    }
    while(ptr != NULL);
    printf("%d expected %zu\nTotal size: %d\n", i - 1,
            BUFFER_SIZE / (size + sizeof(blk_struct)), total);
}

int main(void)
{
    test_asalloc();
    return 0;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T10:04:43+00:00Added an answer on June 15, 2026 at 10:04 am

    I can see some problems with your asfree.

    You need to subtract sizeof(blk_struct) when looking for block head. As allocated data the user wants to free are right behind the header and you have pointer to that data, not the header.

    The second problem is what to do when you get the header. You cannot just call free on the data. You need to have some flag in the header and mark the block as free. And next time you try to allocate a block you need to be able to reuse free blocks, not just creating new blocks at the end. It is also good to be able to split a large free block into two smaller. To avoid fragmentation is is needed to merge neighbour free blocks to one larger.

    Currently I am writing an OS as a school project. I recommend you to use simple alocator working like this:

    • Blocks of memory have headers containing links to neighbour blocks and free flag.
    • At the beginning there is one large block with free flag covering whole memory.
    • When malloc is called, blocks are searched from first to last. When large enough block is found it is split into two(allocated one and free reminder). Pointer to allocated block data is returned.
    • When free is called, matching block is marked as free. If neighbour blocks are also free they are merged.

    I think this is the basic to be able to do malloc and free without fragmentation and loosing memory.

    This is how a structure of headers and footer can look like:

    // Header of a heap block
    typedef struct {
        // Size of the block including header and footer
        size_t size;
    
        // Indication of a free block
        bool free;
    
        // A magic value to detect overwrite of heap header.
        uint32_t magic;
    
    } heap_block_head_t;
    
    
    // Footer of a heap block
    typedef struct {
        // A magic value to detect overwrite of heap footer.
        uint32_t magic;
    
        // Size of the block
        size_t size;
    
    } heap_block_foot_t;
    

    The heap full of blocks with headers and footers like the one above is much like a linked list. Blocks do not describe their neighbours explicitly, but as long as you now they are there you can find them easily. If you have a position of one header then you can add block size to that position and you have a position of a header of the next block.

    // Get next block
    heap_block_head_t *current = ....
    heap_block_head_t *next = (heap_block_head_t*)(((void*) current) + current->size);
    
    // Get previous block
    heap_block_head_t *current = ....
    heap_block_foot_t *prev_foot = (heap_block_foot_t*)(((void*) current) - sizeof(heap_block_foot_t));
    heap_block_head_t *prev = (heap_block_head_t*)(((void*) prev_foot) + sizeof(heap_block_foot_t) - prev_foot->size);
    
    // Not sure if this is correct. I just wanted to illustrate the idea behind.
    // Some extra check for heap start and end are needed
    

    Hope this helps.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I am reading a book about Javascript and jQuery and using one of the
this is what i have right now Drawing an RSS feed into the php,
I have this code to decode numeric html entities to the UTF8 equivalent character.
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.