mercredi 28 mai 2014

c ++ - supprimer pointeur provoque la fuite de mémoire ? -Débordement de pile


I am using Run Time Library, CRT, to detect memory leak. Here is what I found in the destructor:


                    _CrtMemCheckpoint(&crtMemStateFinish);
nDifference = _CrtMemDifference(&crtMemStateDifference, &crtMemStateStart, &crtMemStateFinish);
sizeChange = crtMemStateFinish.lSizes - crtMemStateStart.lSizes;
if(nDifference > 0)
_CrtDumpMemoryLeaks();
nDifference = 0;
sizeChange = 0;
_CrtMemCheckpoint(&crtMemStateStart);


delete[] ptr;
ptr = NULL;

_CrtMemCheckpoint(&crtMemStateFinish);
nDifference = _CrtMemDifference(&crtMemStateDifference, &crtMemStateStart, &crtMemStateFinish);
sizeChange = crtMemStateFinish.lSizes - crtMemStateStart.lSizes;
if(nDifference > 0)
_CrtDumpMemoryLeaks();
nDifference = 0;
sizeChange = 0;
_CrtMemCheckpoint(&crtMemStateStart);

The nDifference > 0, so there is memory leak, but it does not say where.


Here is how ptr is declared and defined:


char ** ptr;

ptr = new char*[4];

Any suggestions?




You are allocating an array of pointers. Not only do you have to delete the array, you have to delete each pointer in the array. Obviously you need to do this before you delete the array.



I am using Run Time Library, CRT, to detect memory leak. Here is what I found in the destructor:


                    _CrtMemCheckpoint(&crtMemStateFinish);
nDifference = _CrtMemDifference(&crtMemStateDifference, &crtMemStateStart, &crtMemStateFinish);
sizeChange = crtMemStateFinish.lSizes - crtMemStateStart.lSizes;
if(nDifference > 0)
_CrtDumpMemoryLeaks();
nDifference = 0;
sizeChange = 0;
_CrtMemCheckpoint(&crtMemStateStart);


delete[] ptr;
ptr = NULL;

_CrtMemCheckpoint(&crtMemStateFinish);
nDifference = _CrtMemDifference(&crtMemStateDifference, &crtMemStateStart, &crtMemStateFinish);
sizeChange = crtMemStateFinish.lSizes - crtMemStateStart.lSizes;
if(nDifference > 0)
_CrtDumpMemoryLeaks();
nDifference = 0;
sizeChange = 0;
_CrtMemCheckpoint(&crtMemStateStart);

The nDifference > 0, so there is memory leak, but it does not say where.


Here is how ptr is declared and defined:


char ** ptr;

ptr = new char*[4];

Any suggestions?



You are allocating an array of pointers. Not only do you have to delete the array, you have to delete each pointer in the array. Obviously you need to do this before you delete the array.


0 commentaires:

Enregistrer un commentaire