[英]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.