【发布时间】:2018-11-22 11:22:24
【问题描述】:
我正在使用“malloc_stats”函数进行一些测试,但我看到了一个我不理解的奇怪行为。测试非常简单,我正在做的是分配内存并在分配之前、分配之后和释放内存之后打印“malloc_stats”。这是我正在使用的代码:
int main(int argc, char *argv[])
{
char *alloc[MAX_ALLOCS];
if ( argc < 3 or strcmp(argv[1], "--help") == 0 ) {
cout << argv[0] << " num-blocks block-size [free-step [start-free [end-free]]]" << endl;
return 1;
}
int numBlocks = atoi(argv[1]);
size_t blockSize = atoi(argv[2]);
int freeStep = (argc > 3) ? atoi(argv[3]) : 1;
int freeBegin = (argc > 4) ? atoi(argv[4]) : 0;
int freeEnd = (argc > 5) ? atoi(argv[5]) : numBlocks;
cout << "============== Before allocating blocks ==============" << endl;
malloc_stats();
for (int j = 0; j < numBlocks; j++)
{
alloc[j] = (char*) malloc(blockSize);
if (alloc[j] == NULL) {
cout << "ERROR: malloc" << endl;
return 1;
}
}
cout << endl << "============== After allocating blocks ==============" << endl;
malloc_stats();
for (int j = freeBegin; j < freeEnd; j += freeStep) {
free(alloc[j]);
}
cout << endl << "============== After freeing blocks ==============" << endl;
malloc_stats();
return 1;
}
这是我得到的输出:
./exe 1000 100 1
============== Before allocating blocks ==============
Arena 0:
system bytes = 135168
in use bytes = 74352
Total (incl. mmap):
system bytes = 135168
in use bytes = 74352
max mmap regions = 0
max mmap bytes = 0
============== After allocating blocks ==============
Arena 0:
system bytes = 270336
in use bytes = 186352
Total (incl. mmap):
system bytes = 270336
in use bytes = 186352
max mmap regions = 0
max mmap bytes = 0
============== After freeing blocks ==============
Arena 0:
system bytes = 270336
in use bytes = 75136
Total (incl. mmap):
system bytes = 270336
in use bytes = 75136
max mmap regions = 0
max mmap bytes = 0
此时,如果我比较分配前和释放后的“in use bytes”,会有784 bytes的差异。
我不明白发生了什么,我认为“使用中的字节”必须相同......这些字节在哪里?
谢谢。
【问题讨论】:
标签: c++ memory-management memory-leaks