开发者

Error deleting large allocations C++

I am trying to delete memory allocation using a function.. The code is as follow...

#include <stdio.h>
#include <iostream>
#include <stdlib.h>

using namespace std;

int NOS, *NO, *SQR;

int Square()
{
    SQR = new int [NOS];
    if (!SQR)
    {
        cout<<"Mem Error SQR \n";
        exit(0);
    }
    for ( int i = 0; i < NOS; i++ )
    {
        SQR[i] = NO[i]*NO[i];
    }
}

void ERASE_MEM()
{
    if (SQR)    delete [] SQR;
    cout<<"Deleted 1\n";
    if (NO != NULL)     delete [] NO;
    cout<<"Deleted 2\n";
}

int main ()
{
    cout<<"Enter No : ";
    cin &g开发者_Python百科t;> NOS;
    NO = new int [NOS];
    if (!NO)    
    {
        cout<<"Mem Error NO \n";
        exit(0);
    }
    for ( int i = 0; i < NOS; i++ )
    {
        NO[i] = 1+i;
    }
    Square();
    delete  NO;
    ERASE_MEM();
}

If the number is less than 15, the program works fine but if the NOS is greater than 15, I get the following error:

* glibc detected ./MEM: double free or corruption (top): 0x097fa008 **

I am doing this in order to create one function for all the memory de-allocations, that I can call while allocating memory. If allocation fails, this function will de-allocate all previous allocations.

Thanks


You are deleting NO twice, once in main and once inside ERASE_MEM. Also, the syntax of delete used in main is wrong, since its an array you should use delete[] (or better remove the statement). BTW, one more thing to note is that when new fails it doesn't return a NULL pointer instead it throws std::bad_alloc exception. So there is no point validating the memory location retunred from new. Also, do not use all capital letters for a function name, the general coding practice is to use the all caps name for macros only. It is also not necessary to check for NULL pointer before calling delete[]. Standard guarantees that deleting a NULL pointer will not do anything.


You delete NO (incorrectly) in the main code and then again (correctly) in ERASE_MEM

edit: calling delete doesn't set pointer to null, it can't do this since the call only gets the value of the pointer, not the pointer itself.
This is a little clearer with the 'C' version free(pData) can't change pData - only what pData points to. A common 'C' idiom is to define your own Free(void **ptr) which you call with Free(&pData) which can then set pData to NULL.
Also note that it's perfectly safe to call free / delete with a null pointer, the function does the check for you.

Don't feel too bad delete and delete [] are a nasty corner of C++, they are function calls that look like statements, and the [] syntax to delete and array is even worse. The only good part is that with smart pointers and modern C++ you never have to use them

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜