![](/img/trans.png)
[英]Is it UB to give a char argument to printf where printf expects a int?
[英]printf and getenv error - expects a char* but argument 2 is of type int
如果應該讓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(或大多數編譯器)啟用更多診斷。 在這種情況下,gcc會說:
warning: implicit declaration of function 'getenv' [-Wimplicit-function-declaration]
MSVC會說:
warning C4013: 'getenv' undefined; assuming extern returning int
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.