정말 예외가 발생할 때 힙에 할당 된 메모리와 무슨 이해가 안 :메모리 누수는 어떻게됩니까?
이#include <iostream>
#include <vector>
using namespace std;
class Base {
private:
int *a;
public:
Base() {
// a = new int[100];
throw runtime_error("err");
}
~Base() {
// delete[] a;
}
};
int main() {
std::vector<Base> bases;
Base base;
bases.push_back(base);
std::cout << bases.size() << std::endl;
return 0;
}
자, 이제, 예외를 throw 단지 비어있는 프로그램입니다. 힙에 메모리를 할당 다음 프로그램 :
#include <iostream>
#include <vector>
using namespace std;
class Base {
private:
int *a;
public:
Base() {
a = new int[100];
throw runtime_error("err");
}
~Base() {
// delete[] a;
}
};
int main() {
std::vector<Base> bases;
Base base;
bases.push_back(base);
std::cout << bases.size() << std::endl;
return 0;
}
프로그램 1 :
==14151== HEAP SUMMARY:
==14151== in use at exit: 72,876 bytes in 3 blocks
==14151== total heap usage: 4 allocs, 1 frees, 72,908 bytes allocated
==14151==
==14151== Searching for pointers to 3 not-freed blocks
==14151== Checked 116,088 bytes
==14151==
==14151== 144 bytes in 1 blocks are possibly lost in loss record 2 of 3
==14151== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14151== by 0x4EC641F: __cxa_allocate_exception (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==14151== by 0x400F44: Base::Base() (in /home/twite/CLionProjects/oop_learn/driver1)
==14151== by 0x400E25: main (in /home/twite/CLionProjects/oop_learn/driver1)
==14151==
==14151== LEAK SUMMARY:
==14151== definitely lost: 0 bytes in 0 blocks
==14151== indirectly lost: 0 bytes in 0 blocks
==14151== possibly lost: 144 bytes in 1 blocks
==14151== still reachable: 72,732 bytes in 2 blocks
프로그램 2 :
==14171== HEAP SUMMARY:
==14171== in use at exit: 73,276 bytes in 4 blocks
==14171== total heap usage: 5 allocs, 1 frees, 73,308 bytes allocated
==14171==
==14171== Searching for pointers to 4 not-freed blocks
==14171== Checked 116,096 bytes
==14171==
==14171== 144 bytes in 1 blocks are possibly lost in loss record 2 of 4
==14171== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14171== by 0x4EC641F: __cxa_allocate_exception (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==14171== by 0x400F98: Base::Base() (in /home/twite/CLionProjects/oop_learn/driver2)
==14171== by 0x400E65: main (in /home/twite/CLionProjects/oop_learn/driver2)
==14171==
==14171== LEAK SUMMARY:
==14171== definitely lost: 0 bytes in 0 blocks
==14171== indirectly lost: 0 bytes in 0 blocks
==14171== possibly lost: 144 bytes in 1 blocks
==14171== still reachable: 73,132 bytes in 3 blocks
그래서, 어디 메모리 누수가있어? Valgrind는 메모리 누수에 대해 말하지 않지만 두 번째 프로그램에서 볼 수 있습니다.
예제를 컴파일 할 때 최적화가 해제되어 예기치 않게 최적화되지 않았는지 확인 했습니까? – dasblinkenlight
g ++ -std = C++ 11 -o driver example.cpp 다음 Valgrind를 실행했습니다 : valgrind --leak-check = full -v ./example – TwITe
'-O0' (대문자 "O"다음에 0이 붙는다) 플래그를'g ++'줄에 추가하고,'valgrind'를 다시 실행한다. – dasblinkenlight