开发者

Buffer Overrun Issues VC++

开发者 https://www.devze.com 2022-12-27 17:28 出处:网络
When i execute my code i am getting this error LPTSTR lpBuffer; ::GetLogicalDriveStrings(1024,lpBuffer);

When i execute my code i am getting this error

LPTSTR lpBuffer;
::GetLogicalDriveStrings(1024,lpBuffer);
while(*lpBuffer != 开发者_如何转开发NULL)
{
  printf("%s\n", lpBuffer); // or MessageBox(NULL, temp, "Test", 0); or whatever
  lpBuffer += lstrlen(lpBuffer)+1;
  printf("sizeof(lpBuffer) %d\n",lstrlen(lpBuffer));
}

OutPut

C

sizeof(lpBuffer) 3

D

sizeof(lpBuffer) 3

E

sizeof(lpBuffer) 3

F

sizeof(lpBuffer) 0


lpBuffer points to random memory. You need something like this:

LPTSTR lpBuffer = new TCHAR[1025];

edit: Corrected the array size to be 1025 instead of 1024, because the length parameter is 1024. This API requires careful reading.


You are supposed to pass a memory address where the string will be copied. However you have not allocated any space for holding the characters. You need to allocate space before passing it to the GetLogicalDriveStrings function. You can allocate the memory on heap as @Windows programmer suppgested or if the maximum length of the string is known at compile time you can allocate it on stack using TCHAR lpBuffer[1024]; Additinally, you are using printf to print the unicode (may be as it depends on compiler flag). This will not work and will print only first character.


You need to actually pass in a buffer - note that the size of the buffer you pass in needs to be one less than the actual size of the buffer to account for the final terminating '\0' character (I have no idea why the API was designed like that).

Here's a slightly modified version of your example:

#include <windows.h>
#include <tchar.h>
#include <stdio.h>

enum {
    BUFSIZE = 1024
};

int _tmain (int argc, TCHAR *argv[])
{
    TCHAR szTemp[BUFSIZE];
    LPTSTR lpBuffer = szTemp;   // point lpBuffer to the buffer we've allocated


    szTemp[0] = _T( '\0');  // I'm not sure if this is necessary, but it was
                            //   in the example given for GetLogicalDriveStrings()

    GetLogicalDriveStrings( BUFSIZE-1, lpBuffer);   // note: BUFSIZE minus 1

    while(*lpBuffer != _T('\0'))
    {
      _tprintf( _T("%s\n"), lpBuffer);
      lpBuffer += lstrlen(lpBuffer)+1;
      _tprintf( _T("length of lpBuffer: %d\n"),lstrlen(lpBuffer));
    }

    return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消