【发布时间】:2021-11-27 16:30:05
【问题描述】:
我有以下用 C 语言编写的代码:
#include <windows.h>
#include <stdio.h>
WCHAR* test(){
WCHAR var[256];
int nSize = GetEnvironmentVariableW(L"SystemRoot", NULL, 0);
GetEnvironmentVariableW(L"SystemRoot", &var, nSize);
wprintf(L"%s\n", var);
return var;
}
int main() {
WCHAR* var = test();
wprintf(L"%s\n", var);
return 0;
}
当我在 Visual Studio 中编译并运行它时,它按预期工作。它打印结果两次 - 在主函数和测试中。输出是:
C:\Windows
C:\Windows
但是当我通过命令使用mingw编译器在linux上编译它时
i686-w64-mingw32-gcc -o test.exe -O3 -Os -static -s test.c
它在启动后给出这个输出:
C:\Windows
(null)
为什么在我使用 mingw 时 test() 函数返回 NULL 以及如何使其正常工作? 谢谢。
【问题讨论】:
-
var指向的数组是一个局部变量,离开函数后就不存在了,所以返回没有意义。您在这里有未定义的行为。它似乎可以在 Windows 上运行纯属偶然。 -
您是否阅读了编译器在编译此代码时向您显示的警告?
-
除了上述 cmets 之外,如果该环境变量超过 255 个字符,则可能会导致缓冲区溢出。您应该根据
GetEnvironmentVariableW(L"SystemRoot", NULL, 0)返回的大小分配缓冲区,或者不要调用GetEnvironmentVariableW(L"SystemRoot", NULL, 0),而是在调用GetEnvironmentVariableW(L"SystemRoot", &var, /* actual buffer size here */)时传入实际的缓冲区大小。