Beginner here. Is it possible to get a buffer, for example:
char buffer[1024];
And split it into smaller chunks of memory (random size depending on user input) using malloc until there’s no more space in the buffer? For example: 1st block = 16, 2nd block = 256, 3rd block = 32, etc.. until I reach 1024. Also I would like to create a structure for every block created. I’m using plain C.
Even though I’m not sure if I can do that, I’ve started something:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
int x = 0;
printf("Enter size of block to be allocated: ");
scanf("%d", &x);
/*(need to implement): call the following function until there's no more
space left in the buffer*/
allocate(x);
return 0;
}
void *allocate(size_t size)
{
char buffer[1024];
char *block;
/*The following allocates a block with the size of the user input.
How do I associate it with the buffer?*/
block = (char *) malloc(size + 1);
//Creates a structure. How do I create one for every block created?
typedef struct blk_struct
{
int data;
struct blk_struct *size_blk;
struct blk_struct *next;
}blk_struct;
blk_struct *first;
}
Research I’ve done: Google and SO. Couldn’t find anything on both. Perhaps I’m not searching for the right key words?
Thanks in advance.
Malloc uses its own internal memory management, so it will not sub-allocate from memory that you provide.
There are a number of malloc implementations available (Google “malloc alternatives”) that provide memory management strategies optimized for various use cases (embedded, multiprocessor, debugging). You may well find an existing solution that addresses the underlying problem you are trying to address with this question.