Hi in the tutorial I have been reading I have been Taught to write to the video memory like this but when I exit the application I keep getting an Access violation error Which Refers to the line
theBuffer[x+y*thePitch] = Colour;
why?

Here is my Realtime Message Loop
Code:
	while (1)
	{
		if (PeekMessage(&theMsg,NULL,0,0,PM_REMOVE))
		{
			if (theMsg.message == WM_QUIT)
				break;
			TranslateMessage(&theMsg);
			DispatchMessage(&theMsg);
		}
		// First Of All Clear Structure and the Lock
		memset(&theSurface,0,sizeof(theSurface));
		theSurface.dwSize = sizeof(theSurface);
		lpddsPrimary->Lock(NULL,&theSurface, DDLOCK_WAIT | DDLOCK_SURFACEMEMORYPTR , NULL);

		// Draw at some random spot
		UCHAR * theBuffer = (UCHAR*)theSurface.lpSurface;
		int thePitch = (int) theSurface.lPitch;

		int x = rand()%640;
		int y = rand()%480;
		UCHAR Colour = rand()%256;
		theBuffer[x+y*thePitch] = Colour;
		lpddsPrimary->Unlock(NULL);
	}