基本 C mkstemp 代码中的段错误
segfault in basic C mkstemp code
看来我完全是在误用mkstemp
。无论我如何使用它,我总是会遇到段错误。我用 gcc -ggdb -Wall -Werror main.c
和 运行 编译了下面最基本的程序 ./a.out
#include <stdlib.h>
int main(int argc, char **argv) {
mkstemp("XXXXXX");
return 0;
}
这总是 returns 返回代码 139 并在终端上打印 [1] 23532 segmentation fault ./a.out
。 (23532
总是变化,因为它是 pid)。
我试过了:
- 切换
gcc
的标志(完全 none,之前标志的很多组合,-Wextra
和 -O0
)
- 通过将生成的文件描述符保存在
int
中来更改代码,休眠 5 秒并再次关闭文件描述符。但我什至没有达到睡眠的开始...
现在我没主意了...
来自手册页:
The last six characters of template
must be "XXXXXX"
and these are
replaced with a string that makes the filename unique. Since it will
be modified, template
must not be a string constant, but should be
declared as a character array.
所以需要声明一个字符数组:
char filename[] = "fileXXXXXX";
mkstemp(filename);
看来我完全是在误用mkstemp
。无论我如何使用它,我总是会遇到段错误。我用 gcc -ggdb -Wall -Werror main.c
和 运行 编译了下面最基本的程序 ./a.out
#include <stdlib.h>
int main(int argc, char **argv) {
mkstemp("XXXXXX");
return 0;
}
这总是 returns 返回代码 139 并在终端上打印 [1] 23532 segmentation fault ./a.out
。 (23532
总是变化,因为它是 pid)。
我试过了:
- 切换
gcc
的标志(完全 none,之前标志的很多组合,-Wextra
和-O0
) - 通过将生成的文件描述符保存在
int
中来更改代码,休眠 5 秒并再次关闭文件描述符。但我什至没有达到睡眠的开始...
现在我没主意了...
来自手册页:
The last six characters of
template
must be"XXXXXX"
and these are replaced with a string that makes the filename unique. Since it will be modified,template
must not be a string constant, but should be declared as a character array.
所以需要声明一个字符数组:
char filename[] = "fileXXXXXX";
mkstemp(filename);