gpt4 book ai didi

c - 基本 C mkstemp 代码中的段错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:50:43 24 4
gpt4 key购买 nike

看来我完全误用了mkstemp。无论我如何使用它,我总是会遇到段错误。我用 gcc -ggdb -Wall -Werror main.c 编译了下面最基本的程序并用 ./a.out

运行它
#include <stdlib.h>

int main(int argc, char **argv) {
mkstemp("XXXXXX");
return 0;
}

这总是返回返回代码 139,并在终端上打印 [1] 23532 segmentation fault ./a.out。 (23532 总是变化,因为它是 pid)。

我试过:

  • 切换 gcc 的标志(完全没有,以前标志的很多组合,-Wextra-O0)
  • 通过将生成的文件描述符保存在 int 中来更改代码,休眠 5 秒并再次关闭文件描述符。但我什至没有达到 sleep 的开始...

现在我没主意了...

最佳答案

来自手册页:

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);

关于c - 基本 C mkstemp 代码中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48648386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com