内存分配调试断言错误

时间:2016-04-04 11:13:59

标签: c debugging memory assertion

我得到了一个"调试断言错误"当这段代码用表达式_CrtIsValidHeapPointer(块)编译时,任何人都可以解释为什么会发生这种情况,以及如何解决

typedef struct _POOL
{
    int size;
    void* memory;

} Pool;

Pool * allocatePool(int n)
{

    int *p = (int*)malloc(sizeof(int) * n);

    Pool pool = { sizeof(*p), *p };

    return &pool;

}

void freePool(Pool* pool)
{
    free(pool);
}

3 个答案:

答案 0 :(得分:4)

您的方法中有2个错误:

  1. 返回指向具有自动存储的变量的指针。
  2. 您在不指向动态内存的指针上调用free()
  3. 这意味着您还应该动态地为Pool对象分配空间。在freePool中,您必须释放void *memory指向的内存和Pool *本身。

    Pool *allocatePool(int n)
    {
        Pool *pool = malloc(sizeof *pool);
    
        if (!pool) {
            /* malloc failed, bail out */
            return NULL;
        }
    
        /* Caller is responsible for passing non negative value as n.
           Negative values will have suprising effects. */
        int *p = malloc(sizeof *p * n);
    
        /* Failed malloc, or n was 0 and current implementation returns
           NULL. */
        if (!p) {
            /* Clean up already allocated memory */
            free(pool);
            /* Many dislike multiple return points in a function, but
               I think for this little example it's ok. That, or gotos. */
            return NULL;
        }
    
        /* Storing the size of single item seems dubious. Size of the whole
           allocated area in objects is much more useful. */
        pool->size = n;
        pool->memory = p;
        return pool;    
    }
    

    void freePool(Pool *pool)
    {
        free(pool->memory);
        free(pool);
    }
    

答案 1 :(得分:1)

你需要这个:

Pool * allocatePool(int n)
{
    int *p = malloc(sizeof(int) * n);
    Pool *pool = malloc(sizeof(Pool));
    pool->memory = p;
    pool->size = n;
    return pool;
}

顺便说一句:malloc的演员阵容不是必需的。

答案 2 :(得分:0)

这两个功能

Pool * allocatePool(int n)
{

    int *p = (int*)malloc(sizeof(int) * n);

    Pool pool = { sizeof(*p), *p };

    return &pool;

}

void freePool(Pool* pool)
{
    free(pool);
}

没有意义。

例如,第一个函数返回指向类型Pool的本地对象的指针,该对象在退出函数后不会处于活动状态。此外,此初始化无效

Pool pool = { sizeof(*p), *p };

我认为你至少意味着以下

Pool pool = { n, p };

或者

Pool pool = { n * sizeof( int ), p };

这些功能可以采用以下方式

Pool allocatePool( int n )
{
    Pool pool = { 0, NULL };
    void *p;

    if ( n > 0 && ( p = malloc( n * sizeof( int ) ) ) != NULL )
    {
        pool.size = n;
        pool.memory = p;
    }

    return pool;
}

void freePool( Pool *pool )
{
    free( pool->memory );
    pool->size = 0;
    pool->memory = NULL;
}