• Advertisement

Archived

This topic is now archived and is closed to further replies.

Access Viloation (how Can i eradicate that problem)

This topic is 5065 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

The code that causes error is indicated in the code... i made a simple linklist..But when i try to do it access violation occurs... Note:menu in the code is just a simple menu... with Files-->&Exit and &Close.. Window-->&Repaint Control-->&Restart and &Stop and &Play... And Please Tell These Memory Management thinks like you are telling a 3 years old child.Cause i Can't understand anything..
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <windowsx.h>
#include <mmsystem.h>
#include "resource.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>


/////////////////////////////////////CONSTANTS////////////////////////////////////////////////

const char* const WINDOWCAPTION="One of My Windows";
const char* const CLASSNAME="MY CLASS";

enum GAMESTATE {GAME_INITIALIZE,GAME_START,GAME_RUN,GAME_STOP,GAME_RESTART,GAME_EXIT};

//////////////////////////////////////GLOBALS/////////////////////////////////////////////////

int WindowCounter=0;  // Globally tracks Windows

HINSTANCE SparehInstance=NULL; // hInstance of Application

GAMESTATE StateOfGame=GAME_INITIALIZE; //State of the Game

RECT Ball;     //ball is an ellipse bounded by a square

RECT Concrete;//Concrete is the rectangle that is used by player

int VelocityX;  // Velocity  in X direction

int VelocityY;  // Velociy   in Y direction

////////////////////////////////////DECLERATIONS///////////////////////////////////////////

int GameMain(HWND&);

////////////////////////////////GAME RELEATED STUFF/////////////////////////////////////////

class CSpecialStone  //Special Stones That has Special Effects

{
private:
	int UpXco,UpYco,DownXco,DownYco; //Coordinates of A rectangle up==>upleftco  down=downright

public:
	CSpecialStone* Next;          //Next Special Stone (will be used in a linklist)

	CSpecialStone():UpXco(0),UpYco(0),DownXco(0),DownYco(0),Next(NULL)
	{
	}
	CSpecialStone(int UpX,int Upy,int DownX,int DownY):UpXco(UpX),	UpYco(Upy),DownXco(DownX),
		DownYco(DownY)
	{
	}
	CSpecialStone(int UpX,int Upy,int DownX,int DownY,CSpecialStone* NextStone):UpXco(UpX),
		UpYco(Upy),DownXco(DownX),DownYco(DownY),Next(NextStone)
	{
	}
	void MovebyAdding(int,int,int,int);//Move the rectangle by adding increasin/decreasin Coordinates

	int RetUpX();
	int RetUpY();
	int RetDownX();
	int RetDownY();
};
int CSpecialStone::RetUpX()
{
	return UpXco;
}
int CSpecialStone::RetUpY()
{
	return UpYco;
}
int CSpecialStone::RetDownX()
{
	return DownXco;
}
int CSpecialStone::RetDownY()
{
	return DownYco;
}
void CSpecialStone::MovebyAdding(int UpX,int UpY,int DownX,int DownY)
{
	UpXco+=UpX;
	UpYco+=UpY;
	DownXco+=DownX;
	DownYco+=DownY;
}

class CSpecialStones      // That is a LinkList of Special Stones

{
private:
	CSpecialStone* First;
	static int StoneCounter; //Counts the number of Special Stones

public:
	CSpecialStones():First(NULL)
	{
	}	
	CSpecialStone& operator [](int index);
	CSpecialStone& Create();  //Creates a CSpecialStone by Default Rectangle Size

	CSpecialStone& Delete();  //Deletes the First CSpecialStone(the stone on top)

	CSpecialStone& Create(int UpX,int UpY,int DownX,int DownY);//Overloaded Version..

};
int CSpecialStones::StoneCounter=0;
CSpecialStone& CSpecialStones::operator[](int index)
{
	int TempCounter=StoneCounter;
	int NumberOfTimesToGoBack=StoneCounter-index;
/* To reach The index member of linklist we must go (StoneCounter-index) times back...
   EX: index=2 and StoneCounter=5 to reach 2.member we must go 3(StoneCounter-index) times back
*/  CSpecialStone* SearchedStone=First;   //Note: NOT LIKE THE ARRAYS... THERE WILL BE NO

	do                                    //      CSPecialStones[0] element but if it has 5 

	{                                     //      member THERE WILL BE CSpecialStones[5]...

		SearchedStone=SearchedStone->Next;
		--TempCounter;
	}while(TempCounter==NumberOfTimesToGoBack);
	return (*SearchedStone);
}
CSpecialStone& CSpecialStones::Create()  //Returns the Created stone as a reference

{
	++StoneCounter;
	First->Next=First;
	First=new CSpecialStone(0,0,20,20);
	return *(First);
}
CSpecialStone& CSpecialStones::Delete()  //Returns the Next that became First after destruction

{                                        //of  Old First...

	--StoneCounter;
	CSpecialStone* TempStone=First;  // a tempstone takes the original First to delete

	First=First->Next; //First takes the place of Next Because original First will be deleted

	delete (TempStone);
	return (*First);
}
CSpecialStone& CSpecialStones::Create(int UpX,int UpY,int DownX,int DownY)
{
	++StoneCounter;
	First->Next=First;
	First=new CSpecialStone(UpX,UpY,DownX,DownY);
	return (*First);
} 

////////////////////////////////////WINPROC//////////////////////////////////////////////////


LRESULT CALLBACK WinProc(HWND hwnd,UINT msg,WPARAM wparam,LPARAM lparam)
{
	static GAMESTATE TempGameState=StateOfGame;
	PAINTSTRUCT ps;
	switch(msg)
	{
	case WM_CREATE:
		{
			++WindowCounter;
			return 0;
		}
		break;
	case WM_PAINT:
		{
			HDC hdc;
			hdc=BeginPaint(hwnd,&ps);
			RedrawWindow(hwnd,&ps.rcPaint,NULL,RDW_INVALIDATE);
			EndPaint(hwnd,&ps);
			ReleaseDC(hwnd,hdc);
			return 0;
		}
		break;
	case WM_ACTIVATE:
		{
			HDC hdc=GetDC(hwnd);
			char buffer[60];
			SetTextColor(hdc,RGB(220,220,220));
			switch(wparam)
			{
			case WA_ACTIVE:
				{
					sprintf(buffer,"Window is Activated");
					TextOut(hdc,50,50,buffer,strlen(buffer));
					return 0;
				}
				break;
			case WA_CLICKACTIVE:
				{
					sprintf(buffer,"Window is Activated by Mouse");
					TextOut(hdc,50,50,buffer,strlen(buffer));
					return 0;
				}
				break;
			case WA_INACTIVE:
				{
					sprintf(buffer,"Window is Deactivated");
					TextOut(hdc,50,50,buffer,strlen(buffer));
					return 0;
				}
				break;
			}
			return 0;
		}
		break;
	case WM_KEYDOWN:
		{
			int virtual_code=int(wparam);
			int key_state=int(lparam);
			//Collision Detection if user wants to move the Concrete While Ball and Concrete in

			//contact Ball will move up...

			if( ((Ball.right>Concrete.left)&&(Ball.bottom>Concrete.top)) && 
				(Ball.left<Concrete.right)  )
			{
				Ball.top-=20;
				Ball.bottom-=20;
			}
			switch(virtual_code)
			{
			case VK_RIGHT:
				{
					Concrete.left+=20;
					Concrete.right+=20;
					return 0;
				}
				break;
			case VK_LEFT:
				{
					Concrete.left-=20;
					Concrete.right-=20;
					return 0;
				}
				break;
			case VK_UP:
				{
					Concrete.top-=20;
					Concrete.bottom-=20;
					return 0;
				}
				break;
			case VK_DOWN:
				{
					Concrete.top+=20;
					Concrete.bottom+=20;
					return 0;
				}
				break;
			}
			return 0;
		}
		break;
	case WM_COMMAND:
		{
			switch(wparam)
			{
			case ID_FILES_EXIT:
				{
					PostQuitMessage(0);
					return 0;
				}
			case ID_FILES_CLOSE:
				{
					PostMessage(hwnd,WM_DESTROY,wparam,lparam);
					return 0;
				}
				break;
			case ID_WINDOW_REPAINT:
				{
					PostMessage(hwnd,WM_PAINT,0,0);
					return 0;
				}
				break;
			case ID_CONTROL_RESTART:
				{
					StateOfGame=GAME_INITIALIZE;
					return 0;
				}
				break;
			case ID_CONTROL_STOP:
				{
					TempGameState=StateOfGame;
					StateOfGame=GAME_STOP;
					return 0;
				}
				break;
			case ID_CONTROL_PLAY:
				{
					StateOfGame=TempGameState;
					return 0;
				}
				break;
			}
			return 0;
		}
		break;
	case WM_CLOSE:
		{
			int Answer=0;
			Answer=MessageBox(hwnd,"Are You Sure??","Sure??",MB_YESNO);
			if(Answer==IDYES)
			{
				SendMessage(hwnd,WM_DESTROY,wparam,lparam);
				
			}
			return 0;
		}
		break;
	case WM_DESTROY:
		{

			--WindowCounter;
			if(WindowCounter<=0)
			{
				PostMessage(hwnd,WM_QUIT,wparam,lparam);
			}
			return 0;
		}
		break;
	}
	return (DefWindowProc(hwnd,msg,wparam,lparam));
}


/////////////////////////////////WINPROC////////////////////////////////////////////////////


int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd)
{
	srand(time(NULL));
	SparehInstance=hInstance;
	WNDCLASSEX myclass;
	MSG msg;
	HWND hwnd;
	myclass.cbClsExtra=0;
	myclass.cbSize=sizeof(WNDCLASSEX);
	myclass.cbWndExtra=0;
	myclass.hbrBackground=(HBRUSH) GetStockObject(WHITE_BRUSH);
	myclass.hCursor=LoadCursor(hInstance,MAKEINTRESOURCE(IDC_CURSOR1));
	myclass.hIcon=LoadIcon(hInstance,MAKEINTRESOURCE(IDI_ICON1));
	myclass.hIconSm=LoadIcon(hInstance,MAKEINTRESOURCE(IDI_ICON1));
	myclass.hInstance=hInstance;
	myclass.lpfnWndProc=WinProc;
	myclass.lpszClassName=CLASSNAME;
	myclass.lpszMenuName=NULL;
	myclass.style=CS_HREDRAW|CS_VREDRAW|CS_OWNDC|CS_DBLCLKS;
	if(!(RegisterClassEx(&myclass)))
	{
		MessageBox(NULL,"Registration Error","Reg.Err",MB_OK);
		return 0;
	}
	if(!(hwnd=CreateWindowEx(NULL,CLASSNAME,WINDOWCAPTION,WS_OVERLAPPEDWINDOW|WS_VSCROLL,
		CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,NULL,NULL,hInstance,NULL)))
	{
		MessageBox(NULL,"Creation Error","Crt.Err.",MB_OK);
		return 0;
	}
	SetMenu(hwnd,LoadMenu(hInstance,MAKEINTRESOURCE(IDR_MENU1)));
	ShowWindow(hwnd,SW_MAXIMIZE);
	UpdateWindow(hwnd);
	while(true)
	{
		if(PeekMessage(&msg,hwnd,0,0,PM_REMOVE))
		{
			if(msg.message==WM_QUIT)
			{
				break;
			}
			TranslateMessage(&msg);
			DispatchMessage(&msg);
			GameMain(hwnd);
		}
	}
	return (msg.wParam);
}

////////////////////////////////DEFINATIONS//////////////////////////////////////////////////

int GameMain(HWND& myhwnd)
{
	HDC hdc=GetDC(myhwnd);
	static char buffer[80];   //will be used for Texts....(Score and Life)

	static RECT PlayArea;  // The Area Where The Ball Will be inside

	static HBRUSH ObBrush=CreateSolidBrush(RGB(100,100,100));
	static HPEN  ObPen=CreatePen(PS_SOLID,4,RGB(180,180,180));
	SelectObject(hdc,ObBrush);
	SelectObject(hdc,ObPen);
	static int Life;   //Life of Player

	static long int Score;  //Score of Player

	CSpecialStones PerfectStones;
/***************************************THE LINE BELOW CAUSES ACCESS VIOLATION ERROR WHY??******************************
	static CSpecialStone Perfect1=PerfectStones.Create(30,30,40,40); 
***********************************************************************************************************************/
	while(StateOfGame!=GAME_EXIT)
	{
		switch(StateOfGame)
		{
		case GAME_INITIALIZE:
			{
				GetClientRect(myhwnd,&PlayArea);
				Ball.left=50;         //it is 50*50 square

				Ball.top=50;
				Ball.right=100;
				Ball.bottom=100;
				Concrete.left=500;  // x2-x1=150 ;// The length of Concrete

				Concrete.top=500;   // y2-y1=25;  // The width  of Concrete

				Concrete.right=650;
				Concrete.bottom=525;
				VelocityX=(rand()%10)+10;
				VelocityY=(rand()%10)+10;
				Life=5;
				Score=0;
				StateOfGame=GAME_START;
				return 0;   //We are Returning from Function to continue Event Looop of Windows

			}
			break;
		case GAME_START:
			{
				StateOfGame=GAME_RUN;
				return 0;   //We are Returning from Function to continue Event Looop of Windows

			}
			break;
		case GAME_RUN:
			{
			    int LoopStartTime=GetTickCount();
				Rectangle(hdc,PlayArea.left,PlayArea.top,PlayArea.right,PlayArea.bottom);
				if(Ball.bottom>=PlayArea.bottom)  //To ensure the ball  will be in PlayArea

				{
					VelocityY=-VelocityY;
				}
				if(Ball.right>=PlayArea.right)
				{
					VelocityX=-VelocityX;
				}
				if(Ball.left<=PlayArea.left)
				{
					VelocityX=-VelocityX;
				}
				if(Ball.top<=PlayArea.top)
				{
					VelocityY=-VelocityY;
				}
				if(Concrete.left<=PlayArea.left)  //To ensure the Concrete will be in PlayArea

				{
					Concrete.left=0;
					Concrete.right=150;
				}
				if(Concrete.right>=PlayArea.right)
				{
					Concrete.right=1024;
					Concrete.left=874;
				}
				if(Concrete.top<=PlayArea.top)
				{
					Concrete.top=0;
					Concrete.bottom=25;
				}
				if(Concrete.bottom>=PlayArea.bottom)
				{
					Concrete.bottom=PlayArea.bottom;
					Concrete.top=PlayArea.bottom-25;
				}
				//Collision Detection for Concrete and Ball...

				//That will ensure if the ball and Concrete touched Each other

				if( ((Ball.right>Concrete.left)&&(Ball.bottom>Concrete.top)) && 
					((Ball.left<Concrete.right)) &&(Ball.top<=Concrete.bottom)  )
					//With if Statemen we ensure that ball striked the Concrete from upside

					//or downside

				{
					VelocityY=-VelocityY;//When Ball hit the Concrete Only Y coordinate Velocity

					                     //Will be inverted..(Because it bounces back in Yco..)

				}
				//Score and Life arregment

				if(Ball.top<=PlayArea.top)
				{
					Score+=20;
				}
				if(Ball.bottom>=PlayArea.bottom)
				{
					--Life;
				}
				Ball.left+=VelocityX;
				Ball.top+=VelocityY;
				Ball.right+=VelocityX;
				Ball.bottom+=VelocityY;
				sprintf(buffer,"Life: %d Score:%d",Life,Score);
				TextOut(hdc,20,20,buffer,strlen(buffer));/*
				Rectangle(hdc,Perfect1.RetUpX(),Perfect1.RetUpY(),Perfect1.RetDownX(),Perfect1.RetDownY());*/
				Ellipse(hdc,Ball.left,Ball.top,Ball.right,Ball.bottom);//For ball

				Rectangle(hdc,Concrete.left,Concrete.top,Concrete.right,Concrete.bottom);//For

				if(Life<=0)                                                     //Concrete

				{
					sprintf(buffer,"You Losed...");
					TextOut(hdc,20,20,buffer,strlen(buffer));
					StateOfGame=GAME_EXIT;
				}
				ReleaseDC(myhwnd,hdc);
				while(GetTickCount()-LoopStartTime<16);
				return 0;   //We are Returning from Function to continue Event Looop of Windows

			}
			break;
		case GAME_STOP:
			{
				return 0;
			}
			break;
		case GAME_EXIT:
			{
				return 0;
			}
			break;
		default:
			{
				return 0;
			}
			break;
		}
	}
	return 0;
}
One more thing if you Erase the Code That Causes Error You can see how The Program works..Do not Forget to add Rectangle(Perfect1.RetX()....) line(i have canceled it by commands to compile program...) [edited by - tonymontana on April 13, 2004 5:14:08 PM]

Share this post


Link to post
Share on other sites
Advertisement
If I''m not mistaken, it''s because in create you try to dereference First [the line First->next=First;] which is a null pointer. *boom*

Share this post


Link to post
Share on other sites

  • Advertisement