【问题标题】:triggered breakpoint when free-ing memory释放内存时触发断点
【发布时间】: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 方法调用的修复程序?
  • 你认识迪尔赞吗? stackoverflow.com/questions/36425445/…
  • '我以前在这里看过这个作业。它故意尝试通过执行“存储/检索超出内存末尾”之类的操作来调用未定义行为。对?所以它表现出随机行为并不奇怪。 – 凯勒姆

标签: c breakpoints free


【解决方案1】:

你在store中浪费内存。

您为池分配 560 个字节。

然后你打电话给store(testPool, poolsize-1, sizeof(str), str)

假设sizeof(str) 是 30

store 你基本上是这样做的:

memcpy((char*)pool->memory + 559, object, 30);

因此在分配的内存之后写入 29 个字节,记住 pool-&gt;memory 指向一个只有 560 个字节长的内存片。

这会导致未定义的行为,在大多数情况下导致程序崩溃,无论是立即还是稍后在程序中或其他奇怪的行为。

整个程序都很可疑。

【讨论】:

  • @MartinJames 可能会也可能不会。我们实际上不知道作业是什么。
  • 测试是检查你是否可以分配过去的内存,我大概必须在我的代码中的某个地方进行一些错误检查,如果我误导了你,我很抱歉,但这基本上是家庭作业,我确实很喜欢所有xx的帮助
  • @David,因为我花了一些时间来完成你的部分作业,你至少可以给个赞。
  • @David 基本上如果你写过去分配的内存,你会得到未定义的行为
猜你喜欢
  • 1970-01-01
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-16
  • 2021-11-28
  • 2012-05-03
相关资源
最近更新 更多