所以我试图实现一个简单的内存池作为大学作业的一部分,但是我遇到了在我分配的内存中存储值的麻烦。
这是我的 main.c 文件:
#include <stdio.h>
#include "Pool.h"
int main(int argc, char** argv)
{
Pool* pool = allocate_pool(64);
printf("Pool Size: %d bytes...\n", pool->size_bytes);
int* a = (int*)100;
store_in_pool(pool, 20, sizeof(int), a);
void* ap = retrieve_from_pool(pool, 20, sizeof(int));
printf("%d\n", ap);
free_pool(pool);
return 0;
}
我的 Pool.h 文件:
#ifndef ASSIGNMENT_2_POOL_H
#define ASSIGNMENT_2_POOL_H
typedef struct MemoryPool
{
int size_bytes;
void* data;
} Pool;
Pool* allocate_pool(int size_bytes);
void free_pool(Pool* pool);
void store_in_pool(Pool* pool, int offset_bytes, int size_bytes, void* object);
void* retrieve_from_pool(Pool* pool, int offset_bytes, int size_bytes);
#endif
还有我的 Pool.c 文件:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "Pool.h"
Pool* allocate_pool(int size_bytes)
{
Pool* pool = (Pool*)malloc(sizeof(Pool*));
pool->size_bytes = size_bytes;
pool->data = malloc(size_bytes);
int i = 0;
while(i < pool->size_bytes)
{
void* temp = (int*)pool->data + i++;
temp = 0;
}
return pool;
}
void free_pool(Pool* pool)
{
free(pool->data);
free(pool);
}
void store_in_pool(Pool* pool, int offset_bytes, int size_bytes, void* object)
{
memcpy((void*)((char*)pool->data + offset_bytes), object, size_bytes);
}
void* retrieve_from_pool(Pool* pool, int offset_bytes, int size_bytes)
{
return (void*)((char*)pool->data + offset_bytes);
}
每当我调用包含调用 memcpy 的行的“store_in_pool”时,就会出现问题。我不确定问题是什么,因为我确定我将正确的值传递给函数但是每次尝试运行程序时都会发生分段错误。
问题的原因可能是什么?