calloc / malloc由std :: shared_ptr包装

时间:2013-03-02 13:24:32

标签: c++ malloc smart-pointers calloc

我有一些代码包含使用calloc和malloc进行内存分配的自制哈希表。我想使用带有自定义删除器的shared_ptr修改这些部分,自动释放已分配的内存。 该代码是mmseg中文分段器算法的一部分,它工作得很好,但它是如此混乱,因为它留下了内存泄漏。我正在考虑使用unordered_map等重写代码,但是现在我想进行这些更改。

我在类似的问题上阅读了答案,例如shared_ptr with malloc and freeAccessing calloc'd data through a shared_ptr,但我在下面的代码中使用它时遇到了问题。

我有这些行,我无法使用智能指针包装调用。所以也许有人可以帮我解决这个问题:

struct Word {
    unsigned char nbytes;   /* number of bytes */
    char length;   /* number of characters */
    unsigned short freq;
    char text[word_embed_len];
};

struct Entry {
    Word *word;
    Entry *next;
};

static Entry **new_bins = static_cast<Entry **>(std::calloc(init_size, 
    sizeof(Entry *)));
Entry *entry, ...;
...
new_bins[hash_val] = entry;
....
free(new_bins);

上面的calloc调用我将使用calloc的结果提供共享指针,例如

std::shared_ptr<Entry *> binsPtr(new_bins, freePtr());

如果这是正确的,我不是真的。

mmseg使用带有malloc()的池分配例程,如下所示:

inline void *pool_alloc(int len) {
    void *mem = _pool_base;

    if (len <= _pool_size) {
        _pool_size -= len;
        _pool_base += len;
        return mem;
    }

    _pool_base = static_cast<char *>(std::malloc(REALLOC_SIZE));
    mem = _pool_base;
    _pool_base += len;
    _pool_size = REALLOC_SIZE - len;
    return mem;
}

然后像这样调用分配器:

Entry *entry = bins[h];
...
entry = static_cast<Entry *>(pool_alloc(sizeof(Entry)));
entry->word = word;
entry->next = NULL;
bins[h] = entry;

是否可以修改pool_alloc例程,例如我可以使用共享指针包装malloc()并定义自定义删除器(甚至可以跳过完整的pool_alloc fct并使用shared_ptr),例如

std::shared_ptr<Entry> entry((Entry *)malloc(sizeof(Entry)), freePtr());

struct freePtr {
    void operator()(void* x) {
        free(x); 
    }
};

如果有人可以帮我解决这个问题会很棒。提前谢谢!

更新

我为我的问题编写了一个简单的内存池类,因此所有指针都会自动销毁。 shared_ptr中包装的calloc()似乎工作正常并按预期工作。 Valgrind报告没有更多的内存泄漏和错误。

1 个答案:

答案 0 :(得分:0)

OP写道:

  

我为我的问题编写了一个简单的内存池类,因此所有指针都会自动销毁。 shared_ptr中包装的calloc()似乎工作正常并按预期工作。 Valgrind报告没有更多的内存泄漏和错误。

换句话说,更改代码修复了错误。 :)此问题可以安全删除。