问题描述
我有一个c++程序,它的常驻内存增长缓慢,而它的虚拟内存基本保持不变.那么这是内存泄漏吗?
I have a c++ program, its resident memory increase slowly, whilst its virtual memory remains unchanged basically. So is this a memory leak?
看了一些文章,运行了一些测试,发现如果空闲内存是2G(使用free
命令),然后运行这段代码:
After reading some articles, and running some tests, I find that if the free memory is 2G (use free
command), and run this code:
int main() {
while (1) {
int* a = new int[100000];
}
}
使用top
命令可以看到常驻内存不到2G,保持不变,但是虚拟内存增长这么快.
use top
command to see that the resident memory is less than 2G, and remains unchanged, but virtual memory is increasing so fast.
所以我能不能说
当出现内存泄漏时,必须增加虚拟内存.
when there is a memory leak, the virtual memory must increase.
但是如果常驻内存在上升和下降,虚拟内存保持不变,这不是内存泄漏
but if resident memory is going up and down, virtual memory remain unchanged, it is not the memory leak
我在 linux 上这样做
I do this on linux
我重写了我的代码:
#include <iostream>
int main() {
while (1) {
int* a = new int[100000];
std::memset(a, 0, sizeof(a));
a[0] += 1;
}
}
和免费命令:缓存的已用空闲共享缓冲区总数内存:3 0 3 0 0 0-/+ 缓冲区/缓存:0 3掉期:3 0 3
运行上面的代码时:
PID 用户 PR NI VIRT RES SHR S %CPU %MEM TIME+ 命令
8518 wq 20 0 358g 2.9g 704 R 53.9 73.8 0:09.13 a.out
RES
增加到~3g,然后停止,代码如下:
the RES
increase to ~3g, then stop,also code below:
#include <iostream>
int main() {
while (1) {
int* a = new int[100000];
}
}
所以最后一个问题,常驻内存是怎么增加的,虚拟内存没有增加,能不能说是free memory增加了,os可以分配更多的物理内存给progress
so the final question, in which way the resident memory increase, but not the virtual, can I say that maybe free memory increase, os can allocate more physical memory to the progress
推荐答案
你没有提到你的平台.在像 Linux 这样的系统上,有一个惰性内存分配器.这意味着如果您调用 new
来分配未初始化的内存(与您的 int 数组一样),则将分配虚拟内存,但不会分配物理内存.稍后,如果您确实为内存分配了一个值,它确实会被分配.
You don't mention your platform. On systems like Linux, there is a lazy memory allocator. This means that if you call new
to allocate memory that is not initialized (as with your int array), then virtual memory will be allocated but not physical memory. Later, if you do assign a value to the memory, it does get allocated.
正如 nwp 所说,尝试为您分配的内存分配值(通过使用类似 memset
的东西或使用带有初始化类成员的构造函数的类).
As nwp says, try assigning values to your allocated memory (either by using something like memset
or using a class with a constructor that initializes the class members).
这篇关于C++:当常驻内存缓慢增加时是否存在内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!