缓冲区溢出问题 VC++
当我执行代码时,出现此错误
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
lpBuffer指向随机内存。你需要这样的东西:
编辑:将数组大小更正为1025而不是1024,因为长度参数是1024。这个API需要仔细阅读。
lpBuffer points to random memory. You need something like this:
edit: Corrected the array size to be 1025 instead of 1024, because the length parameter is 1024. This API requires careful reading.
您应该传递一个将复制字符串的内存地址。但是您还没有分配任何空间来容纳字符。您需要先分配空间,然后再将其传递给 GetLogicalDriveStrings 函数。您可以按照 @Windows 程序员的建议在堆上分配内存,或者如果在编译时已知字符串的最大长度,您可以使用
TCHAR lpBuffer[1024];
在堆栈上分配它此外,您正在使用printf
打印 unicode(可能取决于编译器标志)。这不起作用,只会打印第一个字符。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 usingTCHAR lpBuffer[1024];
Additinally, you are usingprintf
to print the unicode (may be as it depends on compiler flag). This will not work and will print only first character.您需要实际传入一个缓冲区 - 请注意,您传入的缓冲区的大小需要比缓冲区的实际大小小一,以考虑最终的终止 '\0' 字符(我不知道为什么 API就是这样设计的)。
这是您的示例的稍微修改的版本:
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: