Unhandled exception at 0x........ in XXXX.exe: 0xC0000005:Access violation reading location 0x......

Unhandled exception at 0x…….. in XXXX.exe: 0xC0000005:Access violation reading location 0x……

对于C++初学者或粗心者,很容易犯如下图所示错误:

《Unhandled exception at 0x........ in XXXX.exe: 0xC0000005:Access violation reading location 0x......》

那么该错误是由什么造成的呢?

答案无疑只有一个,即:读取了本该没有的值或者地址。

那么如何解决呢?

第一件事,检查下你传入的参数是否合法;
第二件事,若malloc了一块内存,必须记得free;

第三件事,你是否赋值了已经溢出的值或地址。

举例说明:

pOrg = pcPicYuvOrg->getLumaAddr();
	for( y = 0; y < height-1; y++ )
	{
		for( x = 0; x < width-1; x++ )
		{
			Pel A[4];
			//2x2
			A[0]=pOrg[x];	A[1]=pOrg[x+1];	
			A[2]=(pOrg+stride)[x];	A[3]=(pOrg+stride)[x+1];

			if( A[0]==255 && A[1]==255 && A[2]==255 && A[3]==255 )
			{
				pOrg[x] = 255;	pOrg[x+1] = 255;
				(pOrg+stride)[x] = 255;	(pOrg+stride)[x+1] = 255;
			}
			else
			{
				pOrg[x] = 0;	pOrg[x+1] = 0;
				(pOrg+stride)[x] = 0;	(pOrg+stride)[x+1] = 0;
			}
			x += 1;
		}
		pOrg += 2*stride;
	}

此代码就会出现上图所示错误。那么如何解决呢?

pOrg = pcPicYuvOrg->getLumaAddr();
	for( y = 0; y < height/2; y++ )
	{
		for( x = 0; x < width-1; x++ )
		{
			Pel A[4];
			//2x2
			A[0]=pOrg[x];	A[1]=pOrg[x+1];	
			A[2]=(pOrg+stride)[x];	A[3]=(pOrg+stride)[x+1];

			if( A[0]==255 && A[1]==255 && A[2]==255 && A[3]==255 )
			{
				pOrg[x] = 255;	pOrg[x+1] = 255;
				(pOrg+stride)[x] = 255;	(pOrg+stride)[x+1] = 255;
			}
			else
			{
				pOrg[x] = 0;	pOrg[x+1] = 0;
				(pOrg+stride)[x] = 0;	(pOrg+stride)[x+1] = 0;
			}
			x += 1;
		}
		pOrg += 2*stride;
	}

很明显,错误的原因在于:赋值了已经溢出的值。

若以后遇到类似问题,可以逐步检查上述提出的“三件事情”即可。

点赞