Free memory from the card. C ++

std::map<int, int> * mp = new std::map<int, int>;
for(int i = 0; i < 999999; i++){
  mp->insert(std::pair<int, int>(i, 999999-i )); 
}
p("created");
//mp->clear();     -     doesn't help either
delete mp;
p("freed");

The problem is this: "delete mp" does nothing. For comparison:

std::vector<int> * vc = new std::vector<int>;
for(int i = 0; i < 9999999; i++){
  vc->push_back(i); 
}
p("created");
delete vc;
p("freed");

frees memory. How to release memory from a card?
PS: p ("string") just pauses the program and waits for input.

+3
source share
4 answers

The RAM used by the application is not an exact way to determine if memory has been freed by semantics.

Free memory is memory that can be reused. Sometimes, however, you do not observe this freed memory directly in what the OS reports as the memory used by our application.

, , .

+9

, :

{
  std::map<int, int> some_map;
}

:

{
  std::map<int, int>* some_map = new std::map<int, int>();
  /* some instructions that do not throw or exit the function */
  delete some_map;
}

, new, . std::map, , .

valgrind . , , , .

+2

, , , . , , , , , 99999999, 99999999 . . - ( , ), , , , , - . , valgrind, , .

+2
source

To determine if you are freeing memory or not, try adding observable effects to the destructors of your object and ... observing them. For example, instead of a map, create a custom class that produces output when the destructor is called. Something like that:

#include <map>
#include <iostream>
#include <utility>

class Dtor{
        int counter;
    public:
        explicit Dtor(int c):counter(c) {std::cout << "Constructing counter: " << counter << std::endl; }
        Dtor(const Dtor& d):counter(d.counter) {std::cout << "Copy Constructing counter: " << counter << std::endl; }
        ~Dtor(){ std::cout << "Destroying counter: " << counter << std::endl; }
};

int main(){
    std::map<int, const Dtor&> * mp = new std::map<int, const Dtor&>;
    for (int i = 0; i < 10; ++i){
        mp -> insert(std::make_pair(i, Dtor(i)));
    }
   delete mp;
   return 0;
}

You will see that deleting the pointer invokes the destructor of your objects, as expected.

+1
source

Source: https://habr.com/ru/post/1749902/


All Articles