Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to properly delete a pointer to array

Tags:

c++

I'm new to C++, and I'm confused about arrays and pointers. Could someone tell me how I can properly delete a pointer. Like for example,

int *foo;
foo = new int[10];

delete foo;

or

delete [] foo;

Thanks.

like image 971
domlao Avatar asked Sep 27 '09 23:09

domlao


Video Answer


1 Answers

It's:

delete[] foo;

Edit: Modern compilers really need you to use the correct delete operator, or they may leak memory or fail to run the proper destructors.

(I earlier stated that it didn't make a difference in practice. About 10 years ago, I tried many different compilers and failed to find one that actually leaked memory if you mistakenly omitted the []. However the howls of the mob - see below - have forced me to re-try my experimentation, and it seems that modern compilers/libc++s really do care.)

like image 122
alex tingle Avatar answered Oct 03 '22 17:10

alex tingle