开发者

Error when deleting allocated memory in C++

开发者 https://www.devze.com 2023-03-01 09:31 出处:网络
I am new to C++ and am trying to understand the proper way to deallocated array开发者_如何学JAVA memory. I am getting the following error when try to delete an allocated pointer array:

I am new to C++ and am trying to understand the proper way to deallocated array开发者_如何学JAVA memory. I am getting the following error when try to delete an allocated pointer array: "pointer being freed was not allocated."

My pointer is defined as:

T * al ;
al = new T[top] ;

While my destructor for the class where the pointer al is defined in is:

for( int i = 0 ; i < current ; i++ )
        delete( al+i ) ;
    delete [] al ;

The destructor for the class T is:

for( int i = 0 ; i < length ; i++ )
        delete( p+1 ) ;
delete [] p ;

Where p is defined as:

char *p ;
length = strlen( str ) ;
p = new char[length] ;
strcpy( p, str ) ;

How to properly allocate memory and/ or how to fix this?


Just use the delete [], not the loop in addition. delete [] will delete each element of the array.

Also, your loop in the class T destructor is trying to delete p+1 instead of p+i


To be specific, you should delete like so:

int *a = new int; // One allocated
delete a;         // So delete one

int *b = new int[50]; // 50 allocated
delete[] b;           // Just use delete[], don't delete every one

int **c = new int*[50]; // 50 pointers to ints
for (int i = 0; i < 50; i++)
    c[i] = new int;     // each c[i] points to a pointer to a new int

for (int i = 0; i < 50; i++)
    delete c[i];
delete[] c;

Use delete when you use new, delete[] when you use new[].


It's actually wrong to do the following:

int *a = new int[50];

// do stuff...

for (int i = 0; i < 50; i++)
   delete &a[i]; // equivalent to delete (a + i);
delete[] a;

You only do a delete[] a, never the delete (a + i).

0

精彩评论

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