这里是初学者。是否可以获取缓冲区,例如:
char buffer[1024];
然后使用 malloc 将它分成更小的内存块(随机大小取决于用户输入)直到缓冲区中没有更多空间?例如:第一个 block = 16,第二个 block = 256,第三个 block = 32,等等。直到我达到 1024。我还想为每个创建的 block 创建一个结构。我正在使用纯 C。
尽管我不确定我是否能做到这一点,但我已经开始了一些事情:
#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;
}
我做过的研究:Google 和 SO。两者都找不到任何东西。也许我没有在寻找正确的关键词? 提前致谢。
最佳答案
Malloc 使用自己的内部内存管理,因此它不会从您提供的内存中进行子分配。
有许多可用的 malloc 实现(Google“malloc alternatives”)提供针对各种用例(嵌入式、多处理器、调试)优化的内存管理策略。您很可能会找到一个现有的解决方案来解决您试图用这个问题解决的根本问题。
关于c - 从缓冲区分配不同的内存块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13588432/