gpt4 book ai didi

c - 在内存中分配特定数量的字节

转载 作者:行者123 更新时间:2023-11-30 20:23:27 25 4
gpt4 key购买 nike

我一直在尝试在内存中分配指定字节数的内存池。当我继续测试该程序时,它每次只会为每个内存池分配一个字节。

   typedef struct _POOL
{
int size;
void* memory;

} Pool;

Pool* allocatePool(int x);
void freePool(Pool* pool);
void store(Pool* pool, int offset, int size, void *object);

int main()
{

printf("enter the number of bytes you want to allocate//>\n");
int x;
int y;
Pool* p;
scanf("%d", &x);
printf("enter the number of bytes you want to allocate//>\n");
scanf("%d", &x);
p=allocatePool(x,y);
return 0;

}



Pool* allocatePool(int x,int y)
{
static Pool p;
static Pool p2;
p.size = x;
p2.size=y;
p.memory = malloc(x);
p2.memory = malloc(y);
printf("%p\n", &p);
printf("%p\n", &p2);
return &p;//return the adress of the Pool


}

最佳答案

池可以在 main 中声明,并与请求的金额一起传递给 allocatePoll 函数,然后返回。

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

typedef struct _POOL
{
size_t size;
void* memory;
} Pool;

Pool allocatePool(Pool in, int x);
Pool freePool(Pool in);

int main()
{
size_t x = 0;
size_t y = 0;
Pool p = { 0, NULL};
Pool p2 = { 0, NULL};

printf("enter the number of bytes you want to allocate//>\n");
scanf ( "%zu", &x);
p=allocatePool(p,x);
printf("%p\n", p.memory);
printf("enter the number of bytes you want to allocate//>\n");
scanf("%zu", &y);
p2=allocatePool(p2,y);
printf("%p\n", p2.memory);

p = freePool ( p);
p2 = freePool ( p2);
return 0;
}

Pool freePool(Pool in)
{
free ( in.memory);
in.memory = NULL;
in.size = 0;
return in;
}

Pool allocatePool(Pool in,size_t amount)
{
in.size = amount;
if ( ( in.memory = malloc(amount)) == NULL && amount != 0) {
printf ( "Could not allocate memory\n");
in.size = 0;
return in;
}
printf("%p\n", in.memory);
return in;//return Pool
}

关于c - 在内存中分配特定数量的字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36129603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com