GDI+ new建立FontFamily指針後用delete出錯的問題和解決方法

在使用GDI+時,我們有時用new建立某些類的指針,在用delete釋放內存時會出現異常,如下面的代碼:

FontFamily fontFamily(L"Arial");
	Gdiplus::Font font(&fontFamily, 8, FontStyleRegular, UnitPixel);
	RectF rectf(10.0f, 10.0f, 500.0f, 500.0f);
	SolidBrush solidbrush(Color(255, 0, 0, 0));

	INT count = 0;
	INT found = 0;
	WCHAR familyName[LF_FACESIZE];
	WCHAR* familyList = NULL;
	FontFamily* pFontFamily = NULL;

	InstalledFontCollection installedFontCollection;
	

	count = installedFontCollection.GetFamilyCount();
	pFontFamily = new FontFamily[count];
	installedFontCollection.GetFamilies(count, pFontFamily, &found);

	familyList = new WCHAR[count*(sizeof(familyName) + 3)];
	
	ZeroMemory(familyList, count*(sizeof(familyName) + 3));

	for (INT j = 0; j < count; ++j)
	{
		pFontFamily[j].GetFamilyName(familyName);
		StringCchCatW(familyList, count*(sizeof(familyName) + 3), familyName);
		StringCchCatW(familyList, count*(sizeof(familyName) + 3),L", " );
	}

	gs->DrawString(familyList, -1, &font, rectf, NULL, &solidbrush);

	delete pFontFamily;
	delete familyList;

上面代碼運行,delete會出錯,通過斷點發現異常點如下圖:


由紅線可知代碼異常是出現在刪除一個對象(FontFamily)指針,而pFontFamily是一個FontFamily對象數組指針,

解決方法是把:

delete pFontFamily;
改成:

delete []pFontFamily;


用new建立其它類指針在delete時出錯也是,要注意你是建立的對象指針(p=new FontFamily)還是對象數組指針(p=new FontFamily[count]),

對象指針用:delete p

對象數組指針用delete []p



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章