Sign in to follow this  
Jouei

Acess Viloation of Array in Dynamicly Allocated Class

Recommended Posts

Jouei    102
First off im useing C++ with the Bloodshed C++ compiler.. a side note is iw ould use the Better VC++ Express compiler buty alas internet conectivaty + Storage is of a conern and nether do i have much of. So i am curreently Writing an OpenGl Manager class witch will become a larger part of something else but when i uses an Array of bool's much like Nehe tut orial and get the virtaul key code for basic input control i get access viloation. I will highlight the below information more throughly. First off my class:

#ifndef OPENGLMANAGER_H
#define OPENGLMANAGER_H

#include <windows.h>								// Header File For Windows
#include <GL\gl.h>							    	// Header File For The OpenGL32 Library
#include <GL\glu.h>						    		// Header File For The GLu32 Library

typedef unsigned int UINT;

class OPENGLMANAGER 
{
      public:
      OPENGLMANAGER(HWND hWnd, UINT Width, UINT Height, UINT Bits, bool FullScreenFlag);  
      GLvoid ReSizeGLScene(GLsizei width, GLsizei height);
      
      ~OPENGLMANAGER(){KillOpenGL();}

      bool	Keys[256];								// Array Used For The Keyboard Routine
                   
      private:
      GLvoid KillOpenGL();
      
      HWND hWndOpenGL;
      HGLRC hRC;					            	// Permanent Rendering Context
      HDC hDC;							            // Private GDI Device Context

      bool	Active;				         			// Window Active Flag Set To TRUE By Default
      bool FullScreen;                              //Used to track fullscreen status
};

#endif


This is how i allocate it to a pointer:

    try
    {
          pOpenGlManager = new OPENGLMANAGER(hwnd,800,600,16,false);
          if(!pOpenGlManager){return 0;}
    }
    catch(bool Check)
    {
    if(Check == false){delete pOpenGlManager; PostQuitMessage(0);}
    }


And now for where it all goes wrong: Acess Violation

case WM_KEYDOWN:				// Is A Key Being Held Down?
{
pOpenGlManager->Keys[wParam] = true;
return 0;						// Jump Back
}

Any ideas or like i have a feeling that this may be Dev being a piece of somthing brown and smelly :) Anywho any ideas Behold the power of the if statment may it make you tremble....

Share this post


Link to post
Share on other sites
Morrandir    304
I hope you at least have access to a debugger. Set a breakpoint on the line
pOpenGlManager->Keys[wParam] = true;

and check the values of wParam (if it's less than 256), and pOpenGlManager (if it points to a valid instance).

Also, what the heck is this supposed to be:


try
{
pOpenGlManager = new OPENGLMANAGER(hwnd,800,600,16,false);
if(!pOpenGlManager){return 0;}
}
catch(bool Check)
{
if(Check == false){delete pOpenGlManager; PostQuitMessage(0);}
}



Why would you throw a boolean as an exception? If an exception is thrown, you already know something is wrong, you don't have to check for it. The thrown exception object should convey information about what went wrong.

Share this post


Link to post
Share on other sites
Jouei    102
Teh Debugger in Dev is poor at best and the value i am reciveing from the wParam is 26 witch is with tolerance as for the execption it is a temp implementaion nothing more it will be overridden later by a struct for
precise error handeling. Since the execution was not haulted at the exeption check there was no problem inializting the Object and it is valid.

So yet again you see why i am at a lose.

ps i should have made a note about the wParam value earlyer i do appologize for that.

Regards Jouei.

Behold the power of the if statment may it make you tremble....

Share this post


Link to post
Share on other sites
Evil Steve    2017
What is the value of pOpenGlManager? What if you add some logging to the constructor and destructor of that class? Are you absolutely positive that it's a valid pointer?

As an aside, I'd mask off the low 8 bits if you're writing a WPARAM into a array of 256 elements. I.e. make it:
pOpenGlManager->Keys[wParam&0xff] = true;
Just to be absolutely sure there's never any overflow.

Share this post


Link to post
Share on other sites
Morrandir    304
Hmm, did you actually check the pointer at that exact location, to see if it's valid, or did you just assume it was since an exception wasn't thrown?

Also, try posting more of your code, preferably all of it if it's not too long.

And, if you really have to use placeholder exception handling, at least throw an std::exception, which has a string parameter for error reporting. Much better than a bool, which will make people who read it (like me) go WTF?

Share this post


Link to post
Share on other sites
Jouei    102
Thanks Evil Steve for the respones. There is a fairly large amount of error
checking in the Constructor and if anything went wrong ther eit would throw an
execption as for the deconstructor if it was called it would actualy post a
quit message so the window would close so that is not being called.

I have debugged the constructor and steped through it and it runs all the way to the end without so much as a hicup so that is not the problem.

I do admit it is a perplexing problem.

I will post the constructor code just to make sure ther eis no booboos:p



#include "OpenGLManager.h"

OPENGLMANAGER::OPENGLMANAGER(HWND hWnd, UINT Width, UINT Height, UINT Bits, bool FullScreenFlag)
{

hWndOpenGL = hWnd;
FullScreen = FullScreenFlag;

if(FullScreen) //If we want full screen
{
DEVMODE dmScreenSettings; // Device Mode
memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared
dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure
dmScreenSettings.dmPelsWidth = Width; // Selected Screen Width
dmScreenSettings.dmPelsHeight = Height; // Selected Screen Height
dmScreenSettings.dmBitsPerPel = Bits; // Selected Bits Per Pixel
dmScreenSettings.dmFields = DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT;

// Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar.
if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL)
{

// If The Mode Fails, Offer Two Options. Quit Or Run In A Window.
if (MessageBox(hWnd,"The Requested Fullscreen Mode Is Not Supported By\n Your Video Card. Use Windowed Mode Instead?","OpenGLManager",MB_YESNO|MB_ICONEXCLAMATION)==IDYES)
{
FullScreen=false; // Select Windowed Mode (Fullscreen=FALSE)
}
else
{
// Pop Up A Message Box Letting User Know The Program Is Closing.
MessageBox(hWnd,"OpenGL could not be setup. \n Program will now close!","ERROR",MB_OK|MB_ICONSTOP);
throw(false);
}

}
else
{
//To do Set window Styles fr full screen
}

}

//Setup our Pixel format for OpenGL

static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be
{
sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor
1, // Version Number
PFD_DRAW_TO_WINDOW | // Format Must Support Window
PFD_SUPPORT_OPENGL | // Format Must Support OpenGL
PFD_DOUBLEBUFFER, // Must Support Double Buffering
PFD_TYPE_RGBA, // Request An RGBA Format
Bits, // Select Our Color Depth
0, 0, 0, 0, 0, 0, // Color Bits Ignored
0, // No Alpha Buffer
0, // Shift Bit Ignored
0, // No Accumulation Buffer
0, 0, 0, 0, // Accumulation Bits Ignored
16, // 16Bit Z-Buffer (Depth Buffer)
0, // No Stencil Buffer
0, // No Auxiliary Buffer
PFD_MAIN_PLANE, // Main Drawing Layer
0, // Reserved
0, 0, 0 // Layer Masks Ignored
};

//Get an OpenGL device context

if (!(hDC=GetDC(hWnd))) // Did We Get A Device Context?
{
KillOpenGL(); // Reset The Display
MessageBox(hWnd,"Could Not Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
throw(false); // Return FALSE
}

GLuint PixelFormat; // Holds The Results After Searching For A Match

//Get a compatable Pixel format
if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format?
{
KillOpenGL(); // Reset The Display
MessageBox(NULL,"Could Not Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
throw(false); // Return FALSE
}

//Set our pixel format to the compatable one
if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format?
{
KillOpenGL(); // Reset The Display
MessageBox(NULL,"Could Not Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION);
throw(false); // Return FALSE
}

//Get a rendering Context
if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context?
{
KillOpenGL(); // Reset The Display
MessageBox(hWnd,"Could Not Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
throw(false); // Return FALSE
}

//Activate our rendering Context

if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context
{
KillOpenGL(); // Reset The Display
MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION);
throw(false); // Return FALSE
}

SetForegroundWindow(hWnd); // Slightly Higher Priority
SetFocus(hWnd); // Sets Keyboard Focus To The Window

ReSizeGLScene(Width, Height); // Set Up Our Perspective GL Screen

//Setup OpenGL now that we have it
glShadeModel(GL_SMOOTH); // Enables Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // Black Background

glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Test To Do

glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations

throw(true);
}

GLvoid OPENGLMANAGER::ReSizeGLScene(GLsizei Width, GLsizei Height)
{

if (Height==0) // Prevent A Divide By Zero By
{
Height=1; // Making Height Equal One
}

glViewport(0, 0, Width, Height); // Reset The Current Viewport

//Select the matrix to modify
glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
glLoadIdentity(); // Reset The Projection Matrix

// Calculate The Aspect Ratio Of The Window
gluPerspective(45.0f,(GLfloat)Width/(GLfloat)Height,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
glLoadIdentity(); // Reset The Modelview Matrix
}

GLvoid OPENGLMANAGER::KillOpenGL()
{

if (FullScreen) // Are We In Fullscreen Mode?
{
ChangeDisplaySettings(NULL,0); // If So Switch Back To The Desktop
ShowCursor(TRUE); // Show Mouse Pointer
}

if (hRC) // Do We Have A Rendering Context?
{

if (!wglMakeCurrent(NULL,NULL)) // Are We Able To Release The DC And RC Contexts?
{
MessageBox(hWndOpenGL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
}

if (!wglDeleteContext(hRC)) // Are We Able To Delete The RC?
{
MessageBox(hWndOpenGL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
}
hRC=NULL; // Set RC To NULL
}

if (hDC && !ReleaseDC(hWndOpenGL,hDC)) // Are We Able To Release The DC
{
MessageBox(hWndOpenGL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION);
hDC=NULL; // Set DC To NULL
}

PostQuitMessage(0);

}





Currently i am not running in fullscreen mode.
there we go :)

EDIT: I am fairly new to dev but there does appear to be a valid Pointer
and as i sead earlyer it is just a temp execption i just put it that
way so i remmber to fix it later :p

Behold the power of the if statment may it make you tremble....

Share this post


Link to post
Share on other sites
Jouei    102
pOpenGlManager is a golbal pointer. I know pOpenGlManager is valid because the debugging mode although primitive and hard to use does say it is ok.

Share this post


Link to post
Share on other sites
Morrandir    304
You have

throw true;

at the end of your constructor. This is very dangerous and you should remove it. It will skip any code up to the catch statement, for example the line where you check if the allocation was successful. Exceptions should only be thrown when there's an error. Do not abuse them to substitute return statements, or to control program flow.

Now, if pOpenGlManager indeed points to a valid instance, we will need even more code, preferably all of it to be able to run and debug it on our own.

Share this post


Link to post
Share on other sites
HomerSp    126
Only two things could be wrong here (the way I see it); 1. pOpenGlManager is not a valid pointer or 2. wParam is out of scope for the Keys array.

Share this post


Link to post
Share on other sites
Jouei    102
Okies So i did not know that about throwing a true. I wish more information
about specific practice is mentinoed in books about when you are doing specific
things. So this is from what i can tell is what happened dev skipped the try
block completly and still sead the Pointer was valid for the life of me i do
not know why but it had a valid adress.. to what i can only fathom i simply
removed the throw at the end of the constructor as it not needed and it seems
to run fine now. Thank you all who posted respones and i do appologize for the
confusion i wish i hade more room for VC++ express as its debugg mode is much
much better.

Well that seems to of done it my first though was that it was a bad pointer but
the debugger let me step through the code as it was " supposidly beging called
all though not really. " I am as much part to blame as Dev's debugg mode and
want to thank you all for your time.

Regard Jouei

Behold the power of the if statment may it make you tremble....

Share this post


Link to post
Share on other sites
Evil Steve    2017
Quote:
Original post by Jouei
Okies So i did not know that about throwing a true. I wish more information
about specific practice is mentinoed in books about when you are doing specific
things. So this is from what i can tell is what happened dev skipped the try
block completly and still sead the Pointer was valid for the life of me i do
not know why but it had a valid adress.. to what i can only fathom i simply
removed the throw at the end of the constructor as it not needed and it seems
to run fine now. Thank you all who posted respones and i do appologize for the
confusion i wish i hade more room for VC++ express as its debugg mode is much
much better.

Well that seems to of done it my first though was that it was a bad pointer but
the debugger let me step through the code as it was " supposidly beging called
all though not really. " I am as much part to blame as Dev's debugg mode and
want to thank you all for your time.
FYI: I'd guess that because you threw from the constructor, the object wasn't correctly allocated, meaning the pointer pointed at an incomplete or dead object.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this