Sono abbastanza nuovo nella gestione della memoria C++ perché diversamente da C, ci sono più ostacoli per liberare tutta la memoria.Come eliminare veramente i vettori
Sto cercando di eliminare con successo un puntatore a vettore di qualsiasi tipo (cioè vettore * dati)
/**
* We test the program in accessing vectors
* with dynamic storage
**/
#include <iostream>
#include <vector> // you must include this to use vectors
using namespace std;
int main (void){
// Now let's test the program with new and delete
// for no memory leaks with vectors (type safe)
// however, just calling delete is not enough to free all memory
// at runtime
vector <int> * test_vect = new vector <int> (10,5);
// Print out its size
cout << "The size of the vector is " << test_vect->size()
<< " elements" << endl;
// run through vector and display each element within boundary
for (long i = 0; i < (long)test_vect->size(); ++i){
cout << "Element " << i << ": " << test_vect->at(i) << endl;
}
delete test_vect;
return EXIT_SUCCESS;
}
Tuttavia, ottengo una perdita di memoria dopo l'utilizzo di valgrind
==2301== HEAP SUMMARY:
==2301== in use at exit: 4,184 bytes in 2 blocks
==2301== total heap usage: 4 allocs, 2 frees, 4,248 bytes allocated
==2301==
==2301== LEAK SUMMARY:
==2301== definitely lost: 0 bytes in 0 blocks
==2301== indirectly lost: 0 bytes in 0 blocks
==2301== possibly lost: 0 bytes in 0 blocks
==2301== still reachable: 4,096 bytes in 1 blocks
==2301== suppressed: 88 bytes in 1 blocks
Come posso essere in grado di sbarazzarsi di tutte le tracce di perdite di memoria con il puntatore al vettore (ad esempio in fase di runtime)?
'vettore * test_vect = ...' sfida lo scopo stesso per cui vettore esiste in primo luogo. –
Nawaz
Perché stai usando i puntatori con i vettori? – Rapptz
"perché a differenza di C, ci sono più ostacoli per liberare tutta la memoria." Wat. – GManNickG