C++语言之“指针使用常见错误”

一、内存泄漏

1.表现:运行时间越长,占用的内存越多,系统越慢。

2.原因:使用new动态分配内存,不再需要后,没有使用配套的delete释放内存空间。

二、指针指向无用单元

#include<iostream>
using namespace std;

int main()
{
	bool* isSunny;
	
	cout << "Is it sunny (y/n)?";
	char userInput = 'y';
	cin >> userInput;
	
	if(userInput == 'y')
	{
		isSunny = new bool;
		*isSunny = true;
		}	
	cout << "Boolean flag sunny says:" << *isSunny << endl;
	
	delete isSunny;
	
	return 0;
 } 

当不进入if语句块时,指针isSunny无效,此时执行

cout << "Boolean flag sunny says:" << *isSunny << endl;

会导致程序崩溃。

三、悬浮指针(迷途指针or失控指针)

即便原先有效的指针,在执行delete之后,指针也变成了无效指针。

四、检查使用new发出的分配请求是否得到满足

1.使用异常(默认方法)

如果内存分配失败,将引发std::bad_alloc异常

try
{
    代码块;
}catch(bad_alloc){
    异常处理代码块;
}

2.不依赖于异常-->使用new的变种new(nothrow)

这个变种内存分配失败时不会引发异常,而返回NULL,通过检查即可确定有效性

#include<iostream>
using namespace std;

int main()
{
	int * pointsToManyNums = new(nothrow) int [0xffffffff];
	
	if(pointsToManyNums)
	{
		cout << "Memory allocation succeed."<< endl;
		delete[] pointsToManyNums;
	}
	else
		cout << "Memory allocation failed.Ending program"<< endl;
		
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/m0_37811192/article/details/81049542