   Access violation! GRRRR
  Unhandled exception at 0x00411c5d in sprites.exe: 0xC0000005: Access violation reading location 0xffffffb7.That be the error this be the problem:I've been reading a book called "Beginning Direct X 9" For you who have been here a long time I would expect you have heard about it from beginners as it's terrible. Luckily I already have an understanding of C++ and Direct X and was able to correct most of the stupid mistakes in the book.Anyway, I'm at a point in the book where it shows how to create sprites. The following code works fine although strechRect returns an error as initSprites hasn't been called:/*********************** Direct X Tutorial ***********************//*---------------------------------------------------------------*//**************************** Includes ***************************/#include &lt;windows.h&gt;#include &lt;d3d9.h&gt;#include &lt;d3dx9.h&gt;#include &lt;d3dx9tex.h&gt;#include &lt;string&gt;#include &lt;iostream&gt;using namespace std;// include the Direct3D Library file#pragma comment (lib, "d3d9.lib")#pragma comment (lib, "d3dx9.lib")/*---------------------------------------------------------------*//***************************** Structs ****************************/struct myStruct{RECT srcRect;// positionint posX; // the X coordinateint posY; // the Y coordinate};myStruct spriteStruct[6];/*---------------------------------------------------------------*//********************* Variable Declerations ********************/// WindowHINSTANCE hInst; // Handle to Hold Window InstanceHWND wndHandle; // Hold Window Handle// Direct 3DLPDIRECT3D9 pD3D; // the Direct3D objectLPDIRECT3DDEVICE9 pd3dDevice; // the Direct3D deviceIDirect3DSurface9* surface = NULL;IDirect3DSurface9* backbuffer = NULL;int SPRITE_WIDTH = 100;int SPRITE_HEIGHT = 100;int SCRN_WIDTH = 800;int SCRN_HEIGHT = 600;RECT src;/*---------------------------------------------------------------*//********************** Function Prototypes **********************/// Window Functionsbool initWindow ( HINSTANCE hInstance ); // window creationLRESULT CALLBACK WndProc ( HWND, UINT, WPARAM, LPARAM); // message handling// Direct 3d Functionsbool initDirect3D( void );void render ( void );void cleanUp ( void );IDirect3DSurface9* getSurfaceFromBitmap(std::wstring filename);bool initSprites(void);/*---------------------------------------------------------------*//*****************************************************************//************************ Main Entry Point ***********************//*****************************************************************/int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd){// Initialize window:if ( !initWindow( hInstance ) ){MessageBox ( NULL, L"Window Initialization Failed!", L"Error!", 0);return false;}// Initialize Direct 3Dif ( !initDirect3D( ) ){MessageBox ( NULL, L"D3D Initialization Failed!", L"Error!", 0);return false;}// Message loop:MSG msg;ZeroMemory( &msg, sizeof( msg ) );// Loop until quitwhile ( msg.message != WM_QUIT ){if ( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ){TranslateMessage( &msg );DispatchMessage( &msg ); //Send to message event handler ( wndProc )}else{render();}}// Clean up resourcescleanUp();// Exit the application with exit valueDrawText(NULL, L"HELLO!", -1, NULL, DT_LEFT);return (int) msg.wParam;}/*****************************************************************//********************** Window initialisation ********************//*****************************************************************/bool initWindow( HINSTANCE hInstance ){// Setting up the Window ClassWNDCLASSEX wcex;wcex.cbSize=sizeof( WNDCLASSEX );// Size of the structurewcex.style=CS_HREDRAW | CS_VREDRAW;// Window stylewcex.lpfnWndProc=(WNDPROC) WndProc;// Window Callback Procedurewcex.cbClsExtra=0;// extra bytes for class ??wcex.cbWndExtra=0;// Extra bytes for instance ??wcex.hInstance=hInstance;// Handle to instancewcex.hIcon=0;// Icon to use with appwcex.hCursor=LoadCursor( NULL, IDC_ARROW);// Default arrow cursorwcex.hbrBackground=(HBRUSH)(COLOR_WINDOW+1);// Background colourwcex.lpszMenuName=NULL;// menu resource name+wcex.lpszClassName=L"Direct X Example";// Class name to createwcex.hIconSm=0;// Handle to small IconRegisterClassEx(&wcex);// Creating the windowwndHandle = CreateWindow (L"Direct X Example",// Window Class to useL"Direct X Example",// Name of the window ( Title Bar Text )WS_EX_TOPMOST | WS_VISIBLE,// style of the window WS_POPUP | 0, 0,// Window x y position800, 600,// Window width and heightNULL,// No parent window, NULL for desktopNULL,// Menu for the app, NULL = NonehInstance,// Handle to app InstanceNULL );// Mesages passed into the app, None// Check that hWnd creation was successfulif ( !wndHandle ) {MessageBox( NULL, L"OMG HWWWND!", L"OMGOMG WTF", 0 );return false;}// Display the windowShowWindow( wndHandle, SW_SHOW );UpdateWindow( wndHandle );return true;}/*****************************************************************//************************ Message Handling ***********************//*****************************************************************/LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam){// Check any available messages from the queueswitch (message){case WM_DESTROY:PostQuitMessage(0);break;case WM_CLOSE:PostQuitMessage(0);break;}// Always return the message to the default window// procedure for further processingreturn DefWindowProc(hWnd, message, wParam, lParam);}/*****************************************************************//******************** Direct X Initialize ************************//*****************************************************************/bool initDirect3D( void ) {pD3D = NULL;pd3dDevice = NULL;// Create D3D Objectif ( NULL == ( pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) ) {MessageBox( NULL, L"D3D Object Creation Failed", L"Error!", 0);return false;}//screenMode = MessageBox( NULL, L"Run in full screen?", L"Full Screen?", 4);//if ( screenMode == 0 ) MessageBox( NULL, L"Answer is 0", L"Hmm", 0);//if ( screenMode == 1 ) MessageBox( NULL, L"Answer is 1", L"Hmm", 0);//if ( screenMode == 2 ) MessageBox( NULL, L"Answer is 2", L"Hmm", 0);//if ( screenMode == 3 ) MessageBox( NULL, L"Answer is 3", L"Hmm", 0);D3DPRESENT_PARAMETERS d3dpp;ZeroMemory( &d3dpp, sizeof( d3dpp ) );d3dpp.Windowed = TRUE;d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;d3dpp.BackBufferCount = 1;d3dpp.BackBufferHeight = SCRN_HEIGHT;d3dpp.BackBufferWidth = SCRN_WIDTH;d3dpp.hDeviceWindow = wndHandle;// create the d3d deviceif( FAILED (pD3D-&gt;CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_REF,wndHandle,D3DCREATE_HARDWARE_VERTEXPROCESSING,&d3dpp,&pd3dDevice ))){MessageBox( NULL, L"Failed to create D3D Device", L"Error!", 0);return false;}surface = getSurfaceFromBitmap(L"sprites.bmp");if (surface == NULL){MessageBox( NULL, L"Failed to create Surface", L"Error!", 0);return false;}return true;}/****************************************************************************** Render(void)*****************************************************************************/void render(void){// This will hold the back bufferIDirect3DSurface9* backbuffer = NULL;if( NULL == pd3dDevice )return;// Clear the back buffer to a black colorpd3dDevice-&gt;Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0 );// Retrieve a pointer to the back bufferpd3dDevice-&gt;GetBackBuffer(0,0,D3DBACKBUFFER_TYPE_MONO, &backbuffer);// Loop through all the spritesfor ( int i = 0; i &lt; 10; i++ ){RECT destRect; // Create a temporary destination RECT// Fill the temporary RECT with data from// the current sprite structuredestRect.left = spriteStruct.posX;destRect.top = spriteStruct.posY;destRect.bottom = destRect.top + SPRITE_HEIGHT;destRect.right = destRect.left + SPRITE_WIDTH;// Draw the sprite to the back bufferpd3dDevice-&gt;StretchRect( surface, &src, backbuffer, &destRect, D3DTEXF_NONE);}// Present the back buffer contents to the displaypd3dDevice-&gt;Present( NULL, NULL, NULL, NULL );}/*****************************************************************//****************** Clean Up (Release) Resources *****************//*****************************************************************/void cleanUp ( void ) {if( pd3dDevice != NULL ) pd3dDevice-&gt;Release( );if( pD3D != NULL ) pD3D-&gt;Release( );return;}/*********************************************************** getSurfaceFromBitmap**********************************************************/IDirect3DSurface9* getSurfaceFromBitmap(std::wstring filename){int height;int width;IDirect3DSurface9* newSurface = NULL;HRESULT hResult;D3DXIMAGE_INFO imageInfo; // holds details concerning this bitmap// Get the width and height info from this bitmaphResult = D3DXGetImageInfoFromFile(filename.c_str(), &imageInfo);// Make sure that the call to D3DXGetImageInfoFromFile succeededif FAILED (hResult){MessageBox( NULL, L"Get info from file failed", L"Error!", 0);return NULL;}height = imageInfo.Height;width = imageInfo.Width;cout &lt;&lt; height &lt;&lt; "\n" &lt;&lt; width;// Create the offscreen surface that will hold the bitmaphResult = pd3dDevice-&gt;CreateOffscreenPlainSurface(width, height, D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, &newSurface,NULL );// Make sure that this function call did not fail; if it did,// exit this functionif ( FAILED( hResult ) ){MessageBox( NULL, L"Create offscreen surface failed", L"Error!", 0);return NULL;}// Load the bitmap into the surface that was created earlierhResult = D3DXLoadSurfaceFromFile( newSurface, NULL, NULL, filename.c_str( ), NULL, D3DX_DEFAULT, 0, NULL );if ( FAILED( hResult ) ) {MessageBox( NULL, L"Create surface from file", L"Error!", 0);return NULL;}return newSurface;}/************************************************************************************** bool initSprites(void)*************************************************************************************/bool initSprites(void){// Loop through 10 sprite structures and initialize themfor (int i = 0; i &lt; 7; i++ ){spriteStruct.srcRect.top = 0;spriteStruct.srcRect.left = i * SPRITE_WIDTH;spriteStruct.srcRect.right = spriteStruct.srcRect.left + SPRITE_WIDTH;spriteStruct.srcRect.bottom = SPRITE_HEIGHT;spriteStruct.posX = rand()% SCRN_WIDTH - SPRITE_WIDTH;spriteStruct.posY = rand()% SCRN_HEIGHT - SPRITE_HEIGHT;}return true;}When I add initSprites() I get the error above at this line in render():/****************************************************************************** Render(void)*****************************************************************************/void render(void){// This will hold the back bufferIDirect3DSurface9* backbuffer = NULL;if( NULL == pd3dDevice )return;// Clear the back buffer to a black colorpd3dDevice-&gt;Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0 ); //&lt;=============== ERRORRRRRR // Retrieve a pointer to the back bufferpd3dDevice-&gt;GetBackBuffer(0,0,D3DBACKBUFFER_TYPE_MONO, &backbuffer);// Loop through all the spritesfor ( int i = 0; i &lt; 10; i++ ){RECT destRect; // Create a temporary destination RECT// Fill the temporary RECT with data from// the current sprite structuredestRect.left = spriteStruct.posX;destRect.top = spriteStruct.posY;destRect.bottom = destRect.top + SPRITE_HEIGHT;destRect.right = destRect.left + SPRITE_WIDTH;// Draw the sprite to the back bufferpd3dDevice-&gt;StretchRect( surface, &src, backbuffer, &destRect, D3DTEXF_NONE);}// Present the back buffer contents to the displaypd3dDevice-&gt;Present( NULL, NULL, NULL, NULL );initSprites();}Unhandled exception at 0x00411c5d in sprites.exe: 0xC0000005: Access violation reading location 0xffffffb7.0xffffffb7 is the value of pd3ddevice, the error also occurs at every pd3ddevice function. How come this is only happening after initSprites() has been called! Thanks Malb :)[Edited by - malborojones on April 9, 2010 9:13:34 AM]
  I didn't read through your code, but it sounds like you use a unassigned pointer. Maybe you already know, but breakpoints are your friends! In case you are using visual studio for example, click at the crash line and place a breakpoint. Let the program run until it pauses at that point. Inspect the variables by hovering your mouse above it... probably something wasn't initialized properly. Ifso, trace that variable back by placing more breakpoints in an earlier stage.   ;  Yep I've done about half an hour of that before posting!! :P But I just noticed something very weird at this line:pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0 );Putting the break at this line I see that the value of pd3dDevice is: pd3dDevice = 0x0019f3c0I though ohh it seems to have fixed itself, but then pressing continue it changes to:pd3dDevice = 0xffffffb7IUnknown = {...}__vfptr = CXX0030: Error: expression cannot be evaluatedany ideas??   ;myStruct spriteStruct[6];That means you have a total of 6 elements, ranging from 0 to 5.for ( int i = 0; i < 10; i++ )for ( int i = 0; i < 7; i++ )That implies you need more than 6 elements. Also use the [ source] tags when posting code, really helps on the eyes and mind:).   ;Quote:Original post by Mussi *** Source Snippet Removed ***that means you have a total of 6 elements, ranging from 0 to 5.My God! I can't believe that's all that was wrong!! Simple mistake.Thanks :)Oh and about that I assumed it was code tags!   ;  Your sprite array is defined as myStruct spriteStruct[6]; //6 spritesBut your for loop in initSprites goes from 0 to 6 (7 in total). Therefore you are running over the end of your array, and by the looks of it trashing your device pointer.EDIT: damn I'm late to the party ... must stop opening so many threads in tabs.   ;Quote:Original post by greksterEDIT: damn I'm late to the party ... must stop opening so many threads in tabs.heheheh :D;  Still having a problem with the strechRect part though :( If anyone fancies taking a look at why that may be failing, I know it's there thats the problem because Ive put the if(FAILED ( stretchRect (blahblah))) around it and it's returning Invalid call!   ;  I cant see anywhere where you initialise the 'src' rectangle you are passing into StretchRect. Are you sure its valid?   ;  should be! It's there somewhere :Pedit:yep it's up there in the variable declerationsseeing as this is a different problem I'll make a new topic for it.[Edited by - malborojones on April 9, 2010 12:22:50 PM]