Unhandled exception error thrown while running the program
Following is the source code of my program, there's no compilation error but when i run it i get the exception Runtime error as in the attached image.
Blockquote
First-chance exception at 0x00000000 in all5.1.exe: 0xC0000005: Access violation executing location 0x00000000.
Unhandled exception at 0x778F1A91 in all5.1.exe: 0xC0000005: Access violation executing location 0x00000000.
Blockquote
#include <conio.h>
#include <allegro5\allegro.h>
#include <allegro5\allegro_native_dialog.h>
#include <allegro5\allegro_font.h>
#include <allegro5\allegro_ttf.h>
#include <allegro5\allegro_image.h>
#include <allegro5\allegro_primitives.h>
const int SCREEN_H = 690;
const int SCREEN_W = 1350;
class background
{
private: int advt_x = 1000, advt_y = SCREEN_H - 100, nw_m_x = 1350; //data cannot be accessed from outside the class
public: ALLEGRO_FONT *size_20 = al_load_font("digital-7.ttf", 20, 2); //loading font file for advt() and nw_title()
public: ALLEGRO_FONT *size_15 = al_load_font("digital-7.ttf", 15, 1); //loading font file for nw_marquee()
public: void bground()
{
ALLEGRO_BITMAP *bgr = al_load_bitmap("bground.jpg"); //loading the background vertex image
if (bgr == NULL) //checking whether the image loaded successfully or not
{
al_show_native_message_box(NULL, "Error", NULL, "Fatal error: Backgroung Missing from disk!!!", NULL, NULL); //if image didn't loaded then print the error message
}
al_draw_bitmap(bgr, 0, 0, NULL); //printing the background image
}
public: void studio()
{
ALLEGRO_BITMAP *anch = al_load_bitmap("anchor.jpg");
if (anch == NULL) //checking whether the image loaded successfully or not
{
al_show_native_message_box(NULL, "Error", NULL, "Fatal error: Anchor Missing from disk!!!", NULL, NULL); //if image didn't loaded then print the error message
}
al_draw_bitmap(anch, SCREEN_W-300, SCREEN_H-500, NULL); //printing the anchor image
}
public: void news_info()
{
ALLEGRO_BITMAP *nwinfo = al_load_bitmap("news_image.jpg");
if (nwinfo == NULL) //checking whether the image loaded successfully or not
{
al_show_native_message_box(NULL, "Error", NULL, "Fatal error: News Media Missing from disk!!!", NULL, NULL); //if image didn't loaded then print the error message
}
al_draw_bitmap(nwinfo, 0, 200, NULL); //printing the News Media
}
public: void ch_logo()
{
ALLEGRO_BITMAP *chlogo = al_load_bitmap("logo_header.jpg");
if (chlogo == NULL) //checking whether the image loaded successfully or not
{
al_show_native_message_box(NULL, "Error", NULL, "Fatal error: News Media Missing from disk!!!", NULL, NULL); //if image didn't loaded then print the error message
}
al_draw_bitmap(chlogo, SCREEN_W-110, 0, NULL); //printing the News Media
}
public: void nw_title()
{
al_draw_rectangle(0, 0, SCREEN_W-110, 72, al_map_rgb(0, 255, 0), 1.0);
al_draw_text(size_20, al_map_rgb(128, 50, 30), 0, 0, 0, "Violence in a Restaurant over the payment of Bill amounting INR 260."); //printing text
}
public: void nw_marquee()
{
int nw_m_text_len = al_get_text_width(size_15, "All news headlines will be displayed in marquee here.");
if (nw_m_x == (0 - nw_m_text_len))
{
nw_m_x = 1000;
}
al_draw_filled_rectangle(0, SCREEN_H-190, SCREEN_W, SCREEN_H-100, al_map_rgb(0, 255, 0));
al_draw_text(size_15, al_map_rgb(128, 50, 30), nw_m_x, SCREEN_H - 140, 0, "All news headlines will be displayed in marquee here.");
nw_m_x--;
}
public: void advt()
{
al_draw_filled_rectangle(0, SCREEN_H-99, SCREEN_W, SCREEN_H, al_map_rgb(90, 110, 0));
al_draw_text(size_20, al_map_rgb(128, 50, 30), advt_x, SCREEN_H-50, 0, "Ads will be shown here.");
advt_x--;
}
}bg;
int main()
{
ALLEGRO_DISPLAY *display = NULL;
if (!al_init())
{
al_show_native_message_box(NULL, "Init error", NULL, "Allegro failed to initialise!!! Program is exiting.", NULL, NULL);
return -1;
}
display = al_create_display(1350, 690);
al_set_window_position(display, 0, 0);
al_set_window_title(display, "New Window");
al_init_font_addon();
al_init_image_addon();
al_init_primitives_addon();
bg.bground();
bg.studio();
bg.ch_logo();
bg.news_info();
while (1 == 1)
{
bg.nw_title();
bg.advt();
bg.nw_marquee();
al_flip_display(); //print from backBuffer to screen and makes things visible
al_rest(3.0);
al_destroy_display(display);
}
_getch();
return 0;
}
Found the error, right after initializing the font add-on, you need to initialize the ttf add-on with al_init_ttf_addon(). What happens is that the font add-on alone does not know how to read the different formats. So it was failing silently when you tried to load the *.ttf fonts.
Your code is a mess. The formatting is bad, and there are quite a few rampant memory leaks.
Every time you call one of your void functions you load a bitmap but never destroy it with al_destroy_bitmap. This means it leaks an entire ALLEGRO_BITMAP every time. Eventually you will run out of memory and it will return NULL.
rlam is correct about calling al_init_font_addon after al_init. If you're using ttf fonts, you also need to call al_init_ttf_addon.
Something else to be wary of is global objects that load allegro resources in a constructor. These will be loaded before al_init is called, and so they will fail.
Related
Windows GDI ImageCapturing application consumes more GDI objects(Around 320 TaskManager) Single Monitor and Encoding using GDI+ image returns User/ Kernal Marshalling Buffer has been overflowed ​ERROR_MARSHALL_OVERFLOW Marshalling Buffer Error
CImage* getCImageFromBuffer(uint8_t *rgbaBuffer, int imgWidth, int imgHeight, int imgBpp)
{
CImage* image = NULL;
try
{
if (rgbaBuffer != NULL)
{
image = new CImage();
image->Create(imgWidth, imgHeight, imgBpp);
BITMAPINFO bitmapInfo = FormBitmapInfo(imgWidth, imgHeight, imgBpp, true);
HRESULT hErrorCode = SetDIBitsToDevice(image->GetDC(), 0, 0, imgWidth, imgHeight, 0, 0, 0, imgHeight,
rgbaBuffer, &bitmapInfo, DIB_RGB_COLORS);
image->ReleaseDC();
if (FAILED(hErrorCode) && image)
{
cout << "FormCImageFromRGBABuffer: SetDibitsToDevice API failed "<< hErrorCode;
delete image;
image = NULL;
}
else if (FAILED(hErrorCode))
{
image = NULL;
}
}
else
{
cout<< "FormCImageFromRGBABuffer failed, rgbaBuffer is null";
}
}
catch(...)
{
cout<< "Exception in FormCImageFromRGBABuffer";
}
return image;
}
I am using the following code to check if a file is being used by another application:
HANDLE fh = CreateFile("D:\\1.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE)
{
MessageBox(NULL, "The file is in use", "Error", 0);
}
If the file is being used by another application, the message box is displayed. However, the message box is also displayed if the file does not exists!
So what should I do to solve this problem, should I also check if the file exists (using another function), or can the parameters of CreateFile() be changed to only return INVALID_HANDLE_VALUE if the file is in use and does exists?
If you wish to find out, which process has a file open, use the Restart Manager. The procedure consists of the following steps (as outlined in Raymond Chen's blog entry How do I find out which process has a file open?):
Create a Restart Manager session (RmStartSession).
Add a file resource to the session (RmRegisterResource).
Ask for a list of all processes affected by that resource (RmGetList).
Close the session (RmEndSession).
Sample code:
#include <Windows.h>
#include <RestartManager.h>
#pragma comment(lib, "Rstrtmgr.lib")
bool IsFileLocked( const wchar_t* PathName ) {
bool isFileLocked = false;
DWORD dwSession = 0x0;
wchar_t szSessionKey[CCH_RM_SESSION_KEY + 1] = { 0 };
if ( RmStartSession( &dwSession, 0x0, szSessionKey ) == ERROR_SUCCESS ) {
if ( RmRegisterResources( dwSession, 1, &PathName,
0, NULL, 0, NULL ) == ERROR_SUCCESS ) {
DWORD dwReason = 0x0;
UINT nProcInfoNeeded = 0;
UINT nProcInfo = 0;
if ( RmGetList( dwSession, &nProcInfoNeeded,
&nProcInfo, NULL, &dwReason ) == ERROR_MORE_DATA ) {
isFileLocked = ( nProcInfoNeeded != 0 );
}
}
RmEndSession( dwSession );
}
return isFileLocked;
}
You need to use GetLastError() to know why CreateFile() failed, eg:
// this is requesting exclusive access to the file, so it will
// fail if the file is already open for any reason. That condition
// is detected by a sharing violation error due to conflicting
// sharing rights...
HANDLE fh = CreateFile("D:\\1.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
if (fh == INVALID_HANDLE_VALUE)
{
switch (GetLastError())
{
case ERROR_PATH_NOT_FOUND:
case ERROR_FILE_NOT_FOUND:
MessageBox(NULL, "The file does not exist", "Error", 0);
break;
case ERROR_SHARING_VIOLATION:
MessageBox(NULL, "The file is in use", "Error", 0);
break;
//...
default:
MessageBox(NULL, "Error opening the file", "Error", 0);
break;
}
}
else
{
// the file exists and was not in use.
// don't forget to close the handle...
CloseHandle(fh);
}
I need to add custom menu items as needed. I found OnInitMenuPopup (WM_INITMENUPOPUP) does what I need but I can't get an icon to show next to the text on the menu? I've tried a 16x16 png graphic using m_MyGraphic as a CPngImage, I've tried attaching it to a CBitmap, I've tried saving the graphic as a .bmp and loading as CBitmap. I've tried not setting the graphic on the load, but then trying to do it with SetMenuItemBitmaps(), I've tried a 13x13 graphic, I've tried a 15x15 graphic (which matches GetMenuCheckMarkDimensions()). Never does a graphic show next to the menu item? What am I doing wrong or missing?
TIA!
void CMainFrame::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu)
{
// add items
if (pPopupMenu && pPopupMenu->GetMenuItemCount() > 0 && pPopupMenu->GetMenuItemID(0) == ID_MY_EXPECTED_ID) {
// loop though and add menu items
for (UINT i=0; i<theApp.m_MyList.GetCount(); i++) {
CString s;
s.Format(_T("%i: %s"), i, theApp.m_MyList[i].String);
MENUITEMINFO mii={};
mii.cbSize=sizeof(mii);
mii.fMask=MIIM_ID|MIIM_STRING|MIIM_BITMAP;
mii.wID=ID_MY_RANGE_0+i;
mii.dwTypeData=s.GetBuffer();
mii.hbmpItem=(HBITMAP)m_MyBitmap.GetSafeHandle();
pPopupMenu->InsertMenuItem(i+1, &mii, TRUE);
// not working above so tried using this as well but it doesn't work either:
//pPopupMenu->SetMenuItemBitmaps(i+1, MF_BYPOSITION, &m_MyBitmap, &m_MyBitmap);
}
}
CFrameWndEx::OnInitMenuPopup(pPopupMenu, nIndex, bSysMenu);
}
I found a work around. First add CMFCToolBarMenuButton::m_bAlwaysCallOwnerDraw=TRUE; somewhere on initialization.
Then handle drawing it:
BOOL CMainFrame::OnDrawMenuImage(CDC* pDC, const CMFCToolBarMenuButton* pMenuButton, const CRect& rectImage)
{
BOOL result=FALSE;
if (pMenuButton->m_nID>=ID_MY_RANGE_0 && pMenuButton->m_nID<=ID_MY_RANGE_N) {
// size to use on menu
CSize sizemenuimage = CMFCToolBar::GetMenuImageSize();
// get size of our bitmap
BITMAP bitmap;
m_MyBitmap.GetBitmap(&bitmap);
// create dc to attach bitmap to
CDC dcmem;
if (dcmem.CreateCompatibleDC(pDC)) {
// attach bitmap to dc
CBitmap * poldbitmap=dcmem.SelectObject(&m_MyBitmap);
if (poldbitmap) {
// Draw bitmap
result=pDC->StretchBlt(rectImage.left+(rectImage.Width()-sizemenuimage.cx)/2,
rectImage.top+(rectImage.Height()-sizemenuimage.cy)/2,
sizemenuimage.cx, sizemenuimage.cy,
&dcmem, 0, 0, bitmap.bmWidth, bitmap.bmHeight, SRCCOPY);
// Select original object
dcmem.SelectObject(poldbitmap);
}
dcmem.DeleteDC();
}
}
return result;
}
Another possible solution (if you already have the bitmaps for toolbar) is:
void CMainFrame::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu)
{
CMDIFrameWnd::OnInitMenuPopup(pPopupMenu, nIndex, bSysMenu);
// TODO: Add your message handler code here
HICON hIcon = AfxGetApp()->LoadIcon(IDR_TESTMETYPE);
pPopupMenu->SetMenuItemBitmaps(ID_FILE_NEW, MF_BYCOMMAND, ConvertIconToBitmap(hIcon), NULL);
...
...
}
where SetMenuItemBitmaps is defined as:
CBitmap* CMainFrame::ConvertIconToBitmap(HICON hIcon)
{
CDC dc;
CBitmap bmp;
CClientDC ClientDC(this);
dc.CreateCompatibleDC(&ClientDC);
bmp.CreateCompatibleBitmap(&ClientDC, 13, 13);
CBitmap* pOldBmp = (CBitmap*)dc.SelectObject(&bmp);
::DrawIconEx(dc.GetSafeHdc(), 0, 0, hIcon, 13, 13, 0, (HBRUSH)RGB(255, 255, 255), DI_NORMAL);
dc.SelectObject(pOldBmp);
dc.DeleteDC();
HBITMAP hBitmap = (HBITMAP)::CopyImage((HANDLE)((HBITMAP)bmp),
IMAGE_BITMAP, 0, 0, LR_DEFAULTSIZE);
return CBitmap::FromHandle(hBitmap);
}
I am creating a CWinThread that will have it's own GUI. When I create a CWnd on that thread, it displays, but I can't move the window. I am sure that the message pump is running, because I can performn MoveWindow from another thread, and the window moves.
UIThread.h
#pragma once
class CUIThread : public CWinThread
{
public:
DECLARE_DYNCREATE(CUIThread)
CUIThread();
// Attributes
public:
HWND hwnd;
// Operations
public:
void KillThread();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CGDIThread)
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CUIThread();
protected:
virtual BOOL InitInstance();
// Generated message map functions
//{{AFX_MSG(CUIThread)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
UIThread.cpp
#include "stdafx.h"
#include "UIThread.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CUIThread
IMPLEMENT_DYNCREATE(CUIThread, CWinThread)
BEGIN_MESSAGE_MAP(CUIThread, CWinThread)
//{{AFX_MSG_MAP(CUIThread)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
CUIThread::CUIThread() : hwnd(NULL)
{
m_bAutoDelete = FALSE;
}
BOOL CUIThread::InitInstance()
{
this->m_pMainWnd = new CWnd;
m_pMainWnd->Create(_T("STATIC"), _T("Hi"), WS_VISIBLE | WS_OVERLAPPEDWINDOW,
CRect(0, 0, 500, 500), CWnd::GetDesktopWindow(), 1234);
this->hwnd = m_pMainWnd->GetSafeHwnd();
return TRUE;
}
CUIThread::~CUIThread()
{
}
void CUIThread::KillThread()
{
// Note: this function is called in the context of
// other threads, not the thread itself.
this->PostThreadMessage(WM_QUIT, 0, 0);
// allow thread to run at higher priority during
// kill process
SetThreadPriority(THREAD_PRIORITY_ABOVE_NORMAL);
WaitForSingleObject(m_hThread, INFINITE);
}
main.cpp
...
CUIThread* pUIThread = static_cast< CUIThread*>(AfxBeginThread(RUNTIME_CLASS(CUIThread)));
getchar();
MoveWindow(pUIThread->hwnd, 100, 100, 500, 500, true); // works
getchar();
CloseWindow(pUIThread->hwnd); // works
getchar();
pUIThread->KillThread(); // works
delete pUIThread;
getchar();
...
I can see the window, I just can't move/maximize/resize it.
I believe you are creating the window the wrong way. You are creating a child window with the desktop as parent window. This should work:
LPCSTR strClass = AfxRegisterWndClass(CS_HREDRAW | CS_VREDRAW | CS_NOCLOSE);
VERIFY(m_pMainWnd->CreateEx(0, strClass, _T("title"), WS_OVERLAPPEDWINDOW | WS_VISIBLE, CRect(0, 0, 500, 500), NULL, 0));
I want to write a simple configurator program based on resources. I use Windows API function to update resources of stub.exe. Application shows no error, but resource isn't added (some times exe file gets corrupted!). When I open stub.exe in ResourceHacker there are no resources.
My code is:
#include <Windows.h>
#define LANGUAGEID 1033
HANDLE hUpdate;
char szStubPath[MAX_PATH];
char DeadCode[] = "0xDEADC0DE";
unsigned int error = 0;
int main()
{
GetCurrentDirectory(MAX_PATH, szStubPath);
lstrcat(szStubPath, "\\stub.exe");
hUpdate = BeginUpdateResource(szStubPath, FALSE);
if(hUpdate == NULL)
{
MessageBox(0, "BeginUpdateResource failed.", 0, MB_OK+MB_ICONERROR);
error = 1;
}
if(UpdateResource(hUpdate, RT_STRING, TEXT("CURRENT"), LANGUAGEID, &DeadCode, 11) == FALSE)
{
MessageBox(0, "UpdateResource failed.", 0, MB_OK+MB_ICONERROR);
error = 1;
}
if(EndUpdateResource(hUpdate, FALSE) == FALSE)
{
MessageBox(0, "EndUpdateResource failed.", 0, MB_OK+MB_ICONERROR);
error = 1;
}
if(error == 0)
{
MessageBox(0, "stub.exe - Resource added.", "Info", 0);
return EXIT_SUCCESS;
}
else
{
MessageBox(0, "stub.exe - Adding resource failed.", "Info", 0);
return EXIT_FAILURE;
}
}
There are no errors, but resource isn't added (some times exe file gets corrupted!), why? What is wrong?
Edit:
I want to add information that stub.exe is written in MASM32 and config.exe is written in Visual C++. Is there a chance that different programming languages makes problems?
Regards, David