Compiler Optimization trap-the global pointer is abnormal multiple times, and the trap is global
Program development will certainly deal with the compiler. Compiler optimization can improve code running, but there may be some unexpected problems. The following is a pitfall I encountered during development. I hope you can learn from it.
Let's talk about Code directly.
1 static unsigned char * s_data = NULL; // store one frame of video data 2 void DoRendering () 3 {4 // D3D11 case 5 if (s_DeviceType = kUnityGfxRendererD3D11 & assign () 6 {7 ID3D11DeviceContext * ctx = NULL; 8 g_D3D11Device-> GetImmediateContext (& ctx ); 9 10 // update native texture from code11 if (g_TexturePointer) 12 {13 ID3D11Texture2D * d3dtex = (ID3D11Texture2D *) g_TexturePointer; 14 D3D11_TEX TURE2D_DESC desc; // Save the texture information 15 d3dtex-> GetDesc (& desc); // obtain the texture information 16 17 // unsigned char * s_data = new unsigned char [desc. width * desc. height * 4]; 18 // char * errorMessage = new char [80]; 19 char errorMessage [80]; 20 21 if (! S_isInitRender) 22 {23 s_data = (unsigned char *) malloc (desc. width * desc. height * 4); 24 InitRender (desc. width, desc. height, 2, errorMessage); // initialize the rendering parameter 25 if (NULL = s_hThread) 26 {27 unsigned threadID; // thread ID28 s_hThread = (HANDLE) _ beginthreadex (NULL, 0, SfpRefreshThread, NULL, 0, & threadID); // The New thread controls the rendering frequency 29} 30} 31 // controls the refresh frequency 32 if (s_refreshFlag & s_isInitRender) 33 {34 if (! RenderTextureWithVideo (desc. width * 4, s_data) 35 {36 ReleaseRender (2); // release Rendering Memory 37 free (s_data); 38 s_data = NULL; 39} 40 ctx-> UpdateSubresource (d3dtex, 0, NULL, s_data, desc. width * 4, 0); 41 s_refreshFlag = false; 42} 43} 44 ctx-> Release (); 45}
A global pointer variable is defined in row 1st. The memory is allocated and released in the function DoRendering. When this function is called multiple times, the memory of the pointer is allocated and released multiple times.
However, in the VC compiler, an error is reported after the second call of the function, but not in the GCC compiler.
So, if you encounter the above situation, try another compiler!