如果getenv应该返回一个指向环境中的值的指针,那么这个程序不应该打印出环境变量的字符串值吗?
#include <stdio.h>
#include <unistd.h>
int main() {
printf("HOME=%s\n",getenv("HOME"));
return 0;
}
编译时收到以下警告:
format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’
当我运行这个程序时,我会遇到一个分段错误。
我正在使用Ubuntu,我想知道这是否与权限或其他形式的安全有关。
最佳答案
您需要#include <stdlib.h>
,因为这里声明了getenv()
。
另外,考虑使用-Wall
选项从gcc或MSVC(或大多数编译器)启用更多诊断。在这种情况下,海合会会会说:
warning: implicit declaration of function 'getenv' [-Wimplicit-function-declaration]
MSVC会说:
warning C4013: 'getenv' undefined; assuming extern returning int