Handmade Hero » Forums » Code » DAY 008 I am getting the following error ----->Exception thrown: read access violation. GlobalSecondaryBuffer was nullptr.
PiedPiper
2 posts
#12512 DAY 008 I am getting the following error ----->Exception thrown: read access violation. GlobalSecondaryBuffer was nullptr.
4 months, 4 weeks ago Edited by Jeroen van Rijn on July 17, 2017, 8:18 a.m. Reason: code block

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
#include <windows.h>
#include <stdint.h>
#include <xinput.h>
#include <dsound.h>

//TWO TYPES OF STATIC VARIABLES 
#define internal static
#define local_persist static
#define global_variable static

//SIGNED INTEGERS
typedef int8_t int8;
typedef int16_t int16;
typedef int32_t int32;
typedef int64_t int64;

typedef int32 bool32;

//UNSIGNED INTEGERS
typedef uint8_t uint8;
typedef uint16_t uint16;
typedef uint32_t uint32;
typedef uint64_t uint64;

//=====================================================================================================

#define X_INPUT_GET_STATE(name) DWORD WINAPI name(DWORD dwUserIndex, XINPUT_STATE *pState)
typedef X_INPUT_GET_STATE(x_input_get_state);
X_INPUT_GET_STATE(XInputGetStateStub) {
	return (0);
}
global_variable x_input_get_state *XInputGetState_ = XInputGetStateStub;
#define XInputGetState XInputGetState_

//======================================================================================================

#define X_INPUT_SET_STATE(name) DWORD WINAPI name(DWORD dwUserIndex, XINPUT_VIBRATION *pVibration)
typedef X_INPUT_SET_STATE(x_input_set_state);
X_INPUT_SET_STATE(XInputSetStateStub) {
	return (0);
}
global_variable x_input_set_state *XInputSetState_ = XInputSetStateStub;
#define XInputSetState XInputSetState_

//======================================================================================================

/*
Direct Sound from "dsound.h"
*/
#define DIRECT_SOUND_CREATE(name) HRESULT WINAPI name( LPCGUID pcGuidDevice, LPDIRECTSOUND *ppDS, LPUNKNOWN pUnkOuter);
typedef DIRECT_SOUND_CREATE(direct_sound_create);

struct win32OffScreenBuffer {

	BITMAPINFO Info;
	void *Memory;
	int Width;
	int Height;
	int Pitch;
	int BytesPerPixel;
};

struct win32WindowDimension{
	int Width;
	int Height;

};
global_variable win32OffScreenBuffer GlobalBackBuffer;
global_variable bool GlobalRunning;
global_variable LPDIRECTSOUNDBUFFER GlobalSecondaryBuffer;



internal void  Win32LoadXInput(void) {
	HMODULE XInputLibrary = LoadLibraryA("xinput1_4.dll");

	if (!XInputLibrary) {
		XInputLibrary = LoadLibraryA("xinput1_3.dll");
		if (XInputLibrary) {
			XInputGetState = (x_input_get_state *)GetProcAddress(XInputLibrary, "XInputGetState");
			if (!XInputGetState) {
				XInputGetState = XInputGetStateStub;
			}
			XInputSetState = (x_input_set_state *)GetProcAddress(XInputLibrary, "XInputSetState");
			if (!XInputSetState) {
				XInputSetState = XInputSetStateStub;
			}
		}
	}

}

internal void Win32InitDSound(HWND Window, int32 SamplesPerSecond, int32 BufferSize) {
	//Load the Library
	HMODULE DSoundLibrary = LoadLibraryA("dsound.dll");

	if (DSoundLibrary) {
		//Get a directsound Object
		direct_sound_create *DirectSoundCreate = (direct_sound_create *)GetProcAddress(DSoundLibrary, "DirectSoundCreate");

		LPDIRECTSOUND DirectSound;
		if (DirectSoundCreate && SUCCEEDED(DirectSoundCreate(0, &DirectSound, 0))) {

			/********************************************************************************
			WAVEFORMATEX structure Info available on MSDN
			https://msdn.microsoft.com/en-us/library/windows/desktop/dd390970(v=vs.85).aspx
			*********************************************************************************/

			WAVEFORMATEX WaveFormat = {};

			WaveFormat.wFormatTag = WAVE_FORMAT_PCM;
			WaveFormat.nChannels = 2;
			WaveFormat.nSamplesPerSec = SamplesPerSecond;
			WaveFormat.nAvgBytesPerSec = WaveFormat.nSamplesPerSec*WaveFormat.nBlockAlign;
			WaveFormat.nBlockAlign = (WaveFormat.nChannels*WaveFormat.wBitsPerSample) / 8;
			WaveFormat.wBitsPerSample = 16;
			WaveFormat.cbSize = 0;
			if (SUCCEEDED(DirectSound->SetCooperativeLevel(Window, DSSCL_PRIORITY))) {
				DSBUFFERDESC BufferDescription = {};
				BufferDescription.dwSize = sizeof(BufferDescription);
				BufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;


				LPDIRECTSOUNDBUFFER PrimaryBuffer;
				if (SUCCEEDED(DirectSound->CreateSoundBuffer(&BufferDescription, &PrimaryBuffer, 0))) {
					HRESULT Error = PrimaryBuffer->SetFormat(&WaveFormat);
					if (SUCCEEDED(Error)) {
						//set format
					}
					else {
						//diagnostics
					}

				}
				else {
					//diagnostics
				}
			}
			else {
				//diagnostics
			}
			//
			DSBUFFERDESC BufferDescription = {};
			BufferDescription.dwSize = sizeof(BufferDescription);
			BufferDescription.dwFlags = 0;
			BufferDescription.dwBufferBytes = BufferSize;
			BufferDescription.lpwfxFormat = &WaveFormat;
			HRESULT Error = DirectSound->CreateSoundBuffer(&BufferDescription, &GlobalSecondaryBuffer, 0);
			if (SUCCEEDED(Error)) {
				// start playing
			}
			else {
				//diagnostics
			}

		}
		else {
			//diagnostics
		}
	}
}
internal win32WindowDimension Win32GetWindowDimension(HWND Window){
	win32WindowDimension Result;
	RECT ClientRect;
	GetClientRect(Window, &ClientRect);
	Result.Width = ClientRect.right - ClientRect.left;
	Result.Height = ClientRect.bottom - ClientRect.top;

	return(Result);
}

internal void RenderWeirdGradient(win32OffScreenBuffer Buffer, int BlueOffSet, int GreenOffSet){	
	
	uint8 *Row = (uint8 *)Buffer.Memory;
	for (int Y = 0; Y < Buffer.Height; ++Y) {
		uint32 *Pixel = (uint32 *)Row;
		for (int X = 0; X < Buffer.Width; ++X) {
			//PIXEL MEMORY RR GG BB XX

			uint8 Blue = (X + BlueOffSet);
			uint8 Green = (Y + GreenOffSet);


			*Pixel++ = ((Green << 8) | Blue);
			
		}
		Row += Buffer.Pitch;
	}
}

internal void Win32ResizeDibSection(win32OffScreenBuffer *Buffer, int Width, int Height) {
	
	if (Buffer->Memory) {
		VirtualFree(Buffer->Memory, 0, MEM_RELEASE);
	}
	Buffer->Width = Width;
	Buffer->Height = Height;
	Buffer->BytesPerPixel = 4;

	Buffer->Info.bmiHeader.biSize = sizeof(Buffer->Info.bmiHeader);
	Buffer->Info.bmiHeader.biWidth = Buffer->Width;
	Buffer->Info.bmiHeader.biHeight = Buffer->Height;
	Buffer->Info.bmiHeader.biPlanes = 1;
	Buffer->Info.bmiHeader.biBitCount = 32;
	Buffer->Info.bmiHeader.biCompression = BI_RGB;

	int BitmapMemorySize = (Buffer->Width*Buffer->Height)*Buffer->BytesPerPixel;
	Buffer->Memory = VirtualAlloc(0, BitmapMemorySize, MEM_COMMIT, PAGE_READWRITE);

	Buffer->Pitch = Width*Buffer->BytesPerPixel;
	
}

internal void Win32DisplayBufferInWindow(win32OffScreenBuffer *Buffer, HDC DeviceContext, int WindowWidth, int WindowHeight) {

	StretchDIBits(DeviceContext,
		/*
		X, Y, Width, Height,
		X, Y, Width, Height,*/
		0, 0, WindowWidth, WindowHeight,
		0, 0, Buffer->Width, Buffer->Height,
		Buffer->Memory,
		&Buffer->Info,
		DIB_RGB_COLORS, SRCCOPY
	);
}

internal LRESULT CALLBACK Win32MainWindowCallback(
	HWND   Window,
	UINT   Massage,
	WPARAM WParam,
	LPARAM LParam)
{
	LRESULT Result = 0;

	switch (Massage) {
	case WM_SIZE:
	{
		win32WindowDimension Dimension = Win32GetWindowDimension(Window);		
		Win32ResizeDibSection(&GlobalBackBuffer, Dimension.Width, Dimension.Height);
	}break;

	case WM_DESTROY:
	{
		GlobalRunning = false;
		//OutputDebugStringA("WM_DESTROY\n");
	}break;

	case WM_SYSKEYUP: 
	{

	}
	case WM_SYSKEYDOWN: 
	{

	}

	case WM_KEYUP:
	{
		uint32 VKCode = WParam;
		bool WasDown = ((LParam & (1 << 30)) != 0);
		bool IsDown = ((LParam & (1 << 31)) == 0);
		if (WasDown != IsDown) {
			if (VKCode == 'W') {

			}
			else if (VKCode == 'A') {

			}
			else if (VKCode == 'S') {

			}
			else if (VKCode == 'D') {

			}
			else if (VKCode == 'Q') {

			}
			else if (VKCode == 'E') {

			}
			else if (VKCode == VK_UP) {

			}
			else if (VKCode == VK_LEFT) {

			}
			else if (VKCode == VK_DOWN) {

			}
			else if (VKCode == VK_RIGHT) {

			}
			else if (VKCode == VK_ESCAPE) {
				OutputDebugStringA("ESCAPE");
				
				if (IsDown) {
					OutputDebugStringA("IsDown");
				}
				if (WasDown) {
					OutputDebugStringA("WasDown");
				}
			}
			else if (VKCode == VK_SPACE) {

			}
		}

		bool32 AltKeyWasDown = (LParam & (1 << 29));
		if ((VKCode == VK_F4) && AltKeyWasDown) {
			GlobalRunning = false;
		}

	}break;

	case WM_KEYDOWN:
	{

	}

	case WM_CLOSE:
	{
		GlobalRunning = false;
		PostQuitMessage(0);
		//OutputDebugStringA("WM_CLOSE\n");
	}break;
	 
	case WM_ACTIVATEAPP:
	{
		OutputDebugStringA("WM_ACTIVATEAPP\n");
	}break;
	
	case WM_PAINT:
	{
		PAINTSTRUCT Paint;
		HDC DeviceContext = BeginPaint(Window, &Paint);
		int X = Paint.rcPaint.left;
		int Y = Paint.rcPaint.top;
		int Height = Paint.rcPaint.bottom - Paint.rcPaint.top;
		int Width = Paint.rcPaint.right - Paint.rcPaint.left;
		//local_persist DWORD Operation = WHITENESS;

		win32WindowDimension Dimension = Win32GetWindowDimension(Window);
		
		Win32DisplayBufferInWindow(&GlobalBackBuffer, DeviceContext, Dimension.Width, Dimension.Height);
		EndPaint(Window, &Paint);

	}break;
	default:
	{
		OutputDebugStringA("default\n");

		Result = DefWindowProcA(Window, Massage, WParam, LParam);
	}break;

	}
	return(Result);
}

int CALLBACK 
WinMain(HINSTANCE Instance, 
	HINSTANCE PrevInstance, 
	LPSTR CommandLine, 
	int ShowCode) {
	Win32LoadXInput();
	WNDCLASSA WindowClass = {};

	//win32WindowDimension Dimension = Win32GetWindowDimension(Window);
	Win32ResizeDibSection(&GlobalBackBuffer, 1280, 720);

	WindowClass.style = CS_HREDRAW | CS_VREDRAW|CS_OWNDC;
	WindowClass.lpfnWndProc = Win32MainWindowCallback;
	WindowClass.hInstance = Instance;
	WindowClass.hIcon;
	WindowClass.lpszClassName = "HandmadeHeroWindowsClass";

	if (RegisterClassA(&WindowClass)) {
		HWND Window = CreateWindowExA(
			0,
			WindowClass.lpszClassName,
			"Window",
			WS_OVERLAPPEDWINDOW | WS_VISIBLE,
			CW_USEDEFAULT,
			CW_USEDEFAULT,
			CW_USEDEFAULT,
			CW_USEDEFAULT,
			0,
			0,
			Instance,
			0);
		if (Window) {
			HDC DeviceContext = GetDC(Window);
			
			//Graphics
			int XOffSet = 0;
			int YOffSet = 0;

			int SamplesPerSecond = 48000;
			int  Hz = 256;
			uint16 RunningSampleIndex = 0;
			int SquareWavePeriod = SamplesPerSecond/Hz;
			int HalfSquareWavePeriod = SquareWavePeriod/2;
			int BytesPerSample = sizeof(int16) * 2;
			int SecondaryBufferSize = SamplesPerSecond*BytesPerSample;
			
			Win32InitDSound(Window, SamplesPerSecond, SecondaryBufferSize);
			//GlobalSecondaryBuffer->Play(0, 0, DSBPLAY_LOOPING);

			GlobalRunning = true;
			MSG Message;
			while (GlobalRunning) {
				MSG Message;
				if (PeekMessage(&Message, 0, 0, 0, PM_REMOVE)) {
					if (Message.message == WM_QUIT) {
						GlobalRunning = false;
					}
					TranslateMessage(&Message);
					DispatchMessage(&Message);
				}
				for (DWORD ControllerIndex = 0; ControllerIndex < XUSER_MAX_COUNT; ControllerIndex++) {
					XINPUT_STATE ControllerState;
					if (XInputGetState(ControllerIndex, &ControllerState) == ERROR_SUCCESS) {

						XINPUT_GAMEPAD *Pad = &ControllerState.Gamepad;

						bool Up = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_UP);
						bool Down = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_DOWN);
						bool Left = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_LEFT);
						bool Right = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_RIGHT);
						bool Start = (Pad->wButtons & XINPUT_GAMEPAD_START);
						bool Back = (Pad->wButtons & XINPUT_GAMEPAD_BACK);
						bool LeftShoulder = (Pad->wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER);
						bool RightShoulder = (Pad->wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER);
						bool AButton = (Pad->wButtons & XINPUT_GAMEPAD_A);
						bool BButton = (Pad->wButtons & XINPUT_GAMEPAD_B);
						bool XButton = (Pad->wButtons & XINPUT_GAMEPAD_X);
						bool YButton = (Pad->wButtons & XINPUT_GAMEPAD_Y);

						int16 StickX = Pad->sThumbLX;
						int16 StickY = Pad->sThumbLY;

						XOffSet += StickX >> 12;
						YOffSet += StickY >> 12;

					}
					else
					{

					}

				}

				RenderWeirdGradient(GlobalBackBuffer, XOffSet, YOffSet);
				/*
				The following function is a IDirectSoundBuffer8 Lock Method
				https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.idirectsoundbuffer8.idirectsoundbuffer8.lock(v=vs.85).aspx
				*/
				DWORD PlayCursor;
				DWORD WriteCursor;

				if ((GlobalSecondaryBuffer->GetCurrentPosition(&PlayCursor, &WriteCursor)))
				{
					DWORD ByteToLock = RunningSampleIndex*BytesPerSample % SecondaryBufferSize;
					DWORD BytesToWrite;

					if(ByteToLock > PlayCursor)
					{
						BytesToWrite = (SecondaryBufferSize - ByteToLock);
						BytesToWrite += PlayCursor;
					}
					else
					{
						BytesToWrite = PlayCursor - ByteToLock;
					}

					/*DWORD WritePointer = ;
					DWORD BytesToWrite = ;*/
					VOID *Region1;
					DWORD Region1Size;
					VOID *Region2;
					DWORD Region2Size;

		

					if ((GlobalSecondaryBuffer->Lock(ByteToLock, BytesToWrite, &Region1, &Region1Size, &Region2, &Region2Size, 0))) 
					{

						DWORD Region1SampleCount = Region1Size / BytesPerSample;
						int16_t *SampleOut = (int16_t *)Region1;
												
						for (DWORD SampleIndex = 0; SampleIndex < Region1SampleCount; ++SampleIndex) 
						{
							
							int16 SampleValue = ((RunningSampleIndex / HalfSquareWavePeriod) % 2) ? 6000 : -6000;
							*SampleOut++ = SampleValue;
							*SampleOut++ = SampleValue;
							++RunningSampleIndex;
						}
						DWORD Region2SampleCount = Region2Size / BytesPerSample;
						SampleOut = (int16 *)Region2;
						for (DWORD SampleIndex = 0; SampleIndex < Region2SampleCount; ++SampleIndex) 
						{
							

							int16 SampleValue = ((RunningSampleIndex / HalfSquareWavePeriod) % 2) ? 6000 : -6000;
							*SampleOut++ = SampleValue;
							*SampleOut++ = SampleValue;
							++RunningSampleIndex;
						}
						GlobalSecondaryBuffer->Unlock(Region1, Region1Size, Region2, Region2Size);
						win32WindowDimension Dimension = Win32GetWindowDimension(Window);
						Win32DisplayBufferInWindow(&GlobalBackBuffer, DeviceContext, Dimension.Width, Dimension.Height);

					}
				}
			}
		}
		else {
			//TODO: Logging
		}
	}

	else {
		//TODO: Logging
	}
	return(0);
}
mmozeiko
Mārtiņš Možeiko
1518 posts
1 project
#12516 DAY 008 I am getting the following error ----->Exception thrown: read access violation. GlobalSecondaryBuffer was nullptr.
4 months, 4 weeks ago Edited by Mārtiņš Možeiko on July 17, 2017, 6:55 a.m.

1) please use [code] bbtags when you are posting large amount of code. Or put it in gist.github.com or similar online place for code snippets. The code you posted is very unreadable due to lack of indentation.

2) on which line does crash happen?

3) what is the value of GlobalSecondaryBuffer variable when crash happens? Use a debugger to examine it.

4) was it secondary buffer successfully created? Check the result of CreateSoundBuffer call. Is it successful?
Kelimion
Jeroen van Rijn
243 posts
3 projects

A big ball of Wibbly-Wobbly, Timey-Wimey _stuff_

#12519 DAY 008 I am getting the following error ----->Exception thrown: read access violation. GlobalSecondaryBuffer was nullptr.
4 months, 4 weeks ago

I've wrapped the post in a code block (and removed the duplicate thread).
mmozeiko
Mārtiņš Možeiko
1518 posts
1 project
#12523 DAY 008 I am getting the following error ----->Exception thrown: read access violation. GlobalSecondaryBuffer was nullptr.
4 months, 4 weeks ago Edited by Mārtiņš Možeiko on July 17, 2017, 9:19 a.m.

Line 114-116:
1
2
3
			WaveFormat.nAvgBytesPerSec = WaveFormat.nSamplesPerSec*WaveFormat.nBlockAlign;
			WaveFormat.nBlockAlign = (WaveFormat.nChannels*WaveFormat.wBitsPerSample) / 8;
			WaveFormat.wBitsPerSample = 16;

You are reading nBlockAlign in line 114, but it is set only on line 115. Same with wBitsPerSample - it is read on line 115, but set only on line 116.

I assume "SetFormat" and "CreateSoundBuffer" calls are simply failing. Verify your return values! Either print out error message, or just do assert on them for now.
PiedPiper
2 posts
#12588 DAY 008 I am getting the following error ----->Exception thrown: read access violation. GlobalSecondaryBuffer was nullptr.
4 months, 3 weeks ago Edited by on July 22, 2017, 4:06 a.m.

1) I apologize for bad code format.

2) The crash happens on line 461

3) Value of GlobalSecondaryBuffer is 0x00000000

Here is the screenshot
http://imgur.com/1cCkliM
owensd
David Owens II
69 posts

A software engineer that enjoys living in enemy territory.

#12609 DAY 008 I am getting the following error ----->Exception thrown: read access violation. GlobalSecondaryBuffer was nullptr.
4 months, 3 weeks ago

Line #148, you're not handling the error. CreateSoundBuffer is failing but you continue on in code regardless.
mmozeiko
Mārtiņš Možeiko
1518 posts
1 project
#12610 DAY 008 I am getting the following error ----->Exception thrown: read access violation. GlobalSecondaryBuffer was nullptr.
4 months, 3 weeks ago

Line 148 is not the error, that's the result of error. As I said above, the error is in line 114.
owensd
David Owens II
69 posts

A software engineer that enjoys living in enemy territory.

#12618 DAY 008 I am getting the following error ----->Exception thrown: read access violation. GlobalSecondaryBuffer was nullptr.
4 months, 3 weeks ago

mmozeiko
Line 148 is not the error, that's the result of error. As I said above, the error is in line 114.


There are multiple reasons why this could be failing. Line 114, as you mentioned is wrong. However, line 148 is where this buffer is supposed to be assigned. Putting a breakpoint in the error handling here would help someone figure out if what the root cause of the error was.