本文介绍了为什么这个代码可能会崩溃在C ++(指针返回)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int& subtraction(int& a,int& b) {
int* pc = new int;
*pc = a - b;
return (*pc);
}
我在Windows上运行这个代码是正确的,但是当I
在Linux上做同样的事情会导致一些问题。
不会导致运行时错误,这是什么问题。
感谢
I run this code on windows it is correct,but when Ido the same thing on Linux it cause some problem.Itdoes not result in a run-time error,what is the problem.Thanks
推荐答案
它有内存泄漏。考虑这种情况
It has memory leak. Consider this case
int a =5, b =7, c =9;
int & d = subtraction(a,subtraction(b,c));
您将丢失由减法(b,c)返回的指针的引用,能够释放变量。
You will lost the reference of the pointer returned by subtraction(b,c) and you would not be able to free the variable.
这篇关于为什么这个代码可能会崩溃在C ++(指针返回)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!