简体   繁体   中英

How to delete a char pointer in c++

So if i declare the following code

int main() {
   char* c = new char[20];
   delete c;
   return 0;
}

Why is it that I get no memory leak? Isn't the correct way to delete

delete[] c;

Both ways work and I get no memory leak in either.

The first way doesn't work. It just sort of looks like it works.

This is known as Undefined Behaviour : C++ doesn't hold your hand if you do something wrong. It allows the compiler to assume you don't make certain kinds of mistakes, because checking for these mistakes would slow your program down.

If you write Undefined Behaviour, your program could do anything . Including:

"Appearing to work perfectly" is actually the worst of these, because you don't realise you have a bug. Until for instance you port to a different platform, or get a new compiler release, or something else changes, and then you start getting odd results, but of course, this piece of code has worked for years, so it can't possibly be your code that is wrong... can it?

Good compilers will complain about some of these types of mistakes anyway, even though they aren't required to, especially if you turn on extra warnings. Also, static analysis tools can help you catch more of these errors. (Just search for that term; making recommendations would be explicitly off-topic here).

Both ways won't work. If you allocate an array using new [], you have to delete it using delete []. Period. It is undefined behavior otherwise.

Note: If the first way compiles and runs, it doesn't mean it is working. It is undefined behavior. Anything can happen. Your program might crash. It might not. Nothing can be said definitively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM