[英]Does getcwd() ignore the size of the buffer and copy it?
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
char wd[10];
if(getcwd(wd,BUFSIZ) == NULL){ //BUFSIZ = 8192
perror("getcwd");
exit(1);
}
printf("wd = %s\n",wd);
}
此 C 代碼在 Ubuntu Linux 20 中運行良好。緩沖區 wd 的大小為 10,但如果我打印 wd,它可以 output 超過大小 10 的字符串。
我認為 function 無論大小都使用 wd 的指針,所以它可以很好地工作,但它也可以打印虛擬字符串。 這樣對嗎?
//編輯:
printf("wd2 = %s\n",wd2); -> printf("wd = %s\n",wd);
你對緩沖區大小getcwd
。
getcwd
不會神奇地知道緩沖區大小。 知道自己大小的緩沖區不是 C 語言功能。 這就是為什么getcwd
需要 size 參數!
所以, getcwd
愉快地寫到數組末尾之外。
在 C 中,這是未定義的行為。 任何事情都可能發生,“任何事情”包括您在這里觀察到的情況。
好吧,讓我們把你理順:
wd
聲明為char[10]
然后嘗試將8192
字節讀入其中——這是行不通的,wd
然后嘗試 output wd2
—— 不會工作,你的編譯器應該向你尖叫錯誤,\\n
是文字"\n"
(兩個\\
是文字'\'
)不是換行符'\n'
#include <limits.h>
和#define _GNU_SOURCE
使PATH_MAX
可用——這是路徑名在您的系統上可以存在的最大長度(如果有的話)——然后使用getcwd()
讀取那么多字節。總而言之,您可以執行以下操作:
#define _GNU_SOURCE /* needed for PATH_MAX */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h> /* needed for PATH_MAX */
int main (void) {
char wd[PATH_MAX]; /* define your buffer with size PATH_MAX */
if (getcwd (wd, PATH_MAX) == NULL) { /* get the same number of bytes */
perror("getcwd");
exit(1);
}
printf ("wd = %s\n", wd); /* output the results using same variable */
}
編譯
使用getcwd.c
中的源代碼並始終使用FULL WARNINGS ENABLED進行編譯,您可以執行以下操作:
$ gcc -Wall -Wextra -pedantic -Wshadow -std=c11 -Ofast -o bin/getcwd getcwd.c
(注意:我在當前目錄中有一個bin
目錄,我將可執行文件放入其中以避免弄亂我的源目錄)
在沒有警告的情況下編譯之前不要接受代碼。 添加-Werror
將警告視為錯誤,這樣您就無法作弊。
示例使用/輸出
運行程序產生:
$ ./bin/getcwd
wd = /home/david/dev/src-c/tmp/debug
如果您還有其他問題,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.