简体   繁体   English

如何在C ++中删除字符指针

[英]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. 这被称为未定义行为 :如果您做错了事,C ++不会牵手。 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 []. 如果使用new []分配数组,则必须使用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. 没有什么可以肯定地说的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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