Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

c++: is there a memory leak when resident memory is increasing slowly?

I have a c++ program, its resident memory increase slowly, whilst its virtual memory remains unchanged basically. So is this a memory leak?

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];
    }
}

use top command to see that the resident memory is less than 2G, and remains unchanged, but virtual memory is increasing so fast.

so whether I can say that

  • 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

Edit: I do this on linux

I rewrite my code:

#include <iostream>
int main() {
    while (1) {
        int* a = new int[100000];
        std::memset(a, 0, sizeof(a));
        a[0] += 1;
    }
}

and free command: total used free shared buffers cached Mem: 3 0 3 0 0 0 -/+ buffers/cache: 0 3 Swap: 3 0 3

when run code above:

PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
8518 wq 20 0 358g 2.9g 704 R 53.9 73.8 0:09.13 a.out

the RES increase to ~3g, then stop,also code below:

    #include <iostream>
int main() {
    while (1) {
        int* a = new int[100000];
    }
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...