Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...