最近一直在看Charlse Petzold的《Windows程序设计》,作为一个新得不能再新的新手,只能先照着书的抄抄源码了,之前的例子一直都很正常,但昨天遇到一个很诡异的BUG。
先看实例源码吧:
1 /*----------------------------------------------------------------- 2 ENVIRON.C -- Environment List Box 3 (c) Charles Petzold,1998 4 Copy by XXXX,2015/1/26 5 ------------------------------------------------------------------*/ 6 7 #include <windows.h> 8 9 #define ID_LIST 1 10 #define ID_TEXT 2 11 12 LRESULT CALLBACK WndProc(HWND hwnd, UINT, WPARAM, LPARAM); 13 14 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) 15 { 16 static TCHAR szAppName[] = TEXT("Environ"); 17 HWND hwnd; 18 MSG msg; 19 WNDCLASS wndclass; 20 21 wndclass.style = CS_VREDRAW | CS_HREDRAW; 22 wndclass.lpfnWndProc = WndProc; 23 wndclass.cbClsExtra = 0; 24 wndclass.cbWndExtra = 0; 25 wndclass.hInstance = hInstance; 26 wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); 27 wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); 28 wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); 29 wndclass.lpszMenuName = NULL; 30 wndclass.lpszClassName = szAppName; 31 32 if (!RegisterClass(&wndclass)) 33 { 34 MessageBox(NULL, TEXT("This program requires Windows NT!"), szAppName, MB_ICONERROR); 35 return 0; 36 } 37 38 hwnd = CreateWindow(szAppName, TEXT("Environment List Box"), WS_OVERLAPPEDWINDOW, 39 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); 40 ShowWindow(hwnd, iCmdShow); 41 UpdateWindow(hwnd); 42 43 while (GetMessage(&msg, NULL, 0, 0)) 44 { 45 TranslateMessage(&msg); 46 DispatchMessage(&msg); 47 } 48 return msg.wParam; 49 } 50 51 52 void FillListBox(HWND hwndList) 53 { 54 int iLength; 55 TCHAR * pVarBlock, *pVarBeg, *pVarEnd, *pVarName; 56 pVarBlock = GetEnvironmentStrings(); //Get pointer to environment block 57 58 while (*pVarBlock) 59 { 60 if (*pVarBlock != '=') //Skip variable names begining with '=' 61 { 62 pVarBeg = pVarBlock; //Beging of variable name 63 while (*(pVarBlock++) != '='); //Scan until '=' 64 pVarEnd = pVarBlock - 1; //Points to '=' sign 65 iLength = pVarEnd - pVarBeg; //Length of variable name 66 67 //Allocate memory for the variable name and terminating 68 //zero.Copy the variable name and append a zero 69 pVarName = calloc(iLength + 1, sizeof(TCHAR)); 70 CopyMemory(pVarName, pVarBeg, iLength * sizeof(TCHAR)); 71 pVarName[iLength] = '