似乎我的取消分配没有按预期进行。
我必须将std :: vector
问题:free(storage[key])
在这里不是正确的选择,我是否还忘了一些额外的释放?因为根据ubuntu的“系统监视器”,在执行该命令后,占用的内存量保持不变。即使重新进入主功能后,程序占用的内存仍约为30MiB,这应该太多了。
我已经在此上使用了valgrind,它似乎没有报告任何内存泄漏。
有趣的事情:如果我反复调用problematic_function()
,则系统监视器中的已占用内存量保持为30 MiB,并且不会增加一倍。
这只是一个“系统监视器”错误吗?
bool problematic_function(std::vector<uint64_t>& hashTableKeys){
// get number of keys
double numberOfKeys = hashTableKeys.size();
// copy keys into char** 'storage', because C-lib wants it like this.
char** storage = (char**)calloc( numberOfKeys, sizeof(char*));
if (storage!=nullptr){ // if calloc() succeeded
for(int key = 0; key < numberOfKeys; key++){
std::string keyString = std::to_string(hashTableKeys[key]);
storage[key] = (char *)calloc( (keyString.length()+1), sizeof(char));
if (storage[key]!=nullptr){ // if calloc() succeeded
std::strcpy(storage[key], keyString.c_str());
}
else{
return false;
}
}
}
else{
return false;
}
// pass the char** to the c-lib-function
// ...
// de-allocate the memory-blocks
for(int key=0; key < numberOfKeys; key++){
free(storage[key]);
}
free(storage);
hashTableKeys.clear();
return true;
}
int main(int argc, char **argv)
{
/*
* checking if memory is freed
*/
int numberOfModelKeys = 1000000;
// construct arbitrary keys
std::vector<uint64_t> hashTableKeys;
for (int i = 0; i < numberOfModelKeys ; i++){
uint64_t hashKey = static_cast<uint64_t>(i);
hashTableKeys.push_back(hashKey);
}
problematic_function(hashTableKeys);
/*
* at this point the occupied memory of the program (as shown in ubuntu's system-monitor)
* is still about 30 MiB, although it probably should be a lot less.
*/
}