【发布时间】:2016-04-05 12:21:57
【问题描述】:
我试图释放这段代码正在使用的内存,但它触发了一个断点,没有任何提示,谁能解释原因
有问题的代码
store(testPool, poolSize - 1, sizeof(str), str);
printf("Test 6: Store / Retrieve past the end of memory\n");
printf("\tStored: %s\n", str);
void* temp = retrieve(testPool, poolSize - 1, sizeof(str) - 1);
if (temp != NULL)
{
printf("\tRetrieved value\n");
}
else
{
printf("\tRetrieved NULL\n");
}
freePool(testPool);
当我试图释放池中的内存时弹出错误,我不知道为什么
void freePool(Pool* pool)
{
if (pool != NULL)
if (pool->memory != NULL)
{
free(pool->memory); //here
free(pool);
}
}
这里是我用固定大小分配池的地方
const int poolSize = 560;
testPool = allocatePool(poolSize);
如果有帮助的话,这里是剩下的代码
typedef struct _POOL
{
int size;
void* memory;
} Pool;
Pool * allocatePool(int n)
{
Pool *pool =(Pool*) malloc(sizeof(Pool));
if(pool != NULL)
pool->memory = malloc(sizeof(char) * n);
if (pool->memory != NULL)
if(n > 0)
pool->size = n;
else
free(pool);
return pool;
}
void store(Pool* pool, int offset, int size, void *object)
{
if (pool != NULL)
if (size < pool->size)
memcpy((char*)pool->memory + offset, object, size);
}
void *retrieve(Pool* pool, int offset, int size)
{
return (char*)pool->memory + offset;
}
【问题讨论】:
-
请发帖MCVE。例如,您甚至没有发布您调用
allocatePool的部分。 -
提示:删除这一行:
store(testPool, poolSize - 1, sizeof(str), str);并查看free是否仍然命中断点。如果不是,那么store很可能会覆盖它不应该覆盖的内存。store中的+ offset看起来很可疑。 -
我已经包含了我分配池 micheal 的位置,您对 store 方法是正确的,我将其注释掉并且没有问题,是否有不需要我更改 store 方法调用的修复程序?
-
'我以前在这里看过这个作业。它故意尝试通过执行“存储/检索超出内存末尾”之类的操作来调用未定义行为。对?所以它表现出随机行为并不奇怪。 – 凯勒姆
标签: c breakpoints free