Search code examples
clinuxgccposix

segfault in basic C mkstemp code


It seems that I'm completely misusing mkstemp. However I use it, I always get a segfault. I compiled the most basic program below with gcc -ggdb -Wall -Werror main.c and ran it with ./a.out

#include <stdlib.h>

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

This always returns the returncode 139 and it prints [1] 23532 segmentation fault ./a.out on the terminal. (23532 always changes because it's the pid).

I tried:

  • switching the flags of gcc (none at all, a lot of combinations of the previous flags, -Wextra and -O0)
  • Changing the code by saving the resulting filedescriptor in a int, sleeping 5 seconds and closing the filedescriptor again. But I don't even reach the start of the sleep...

And now I'm out of ideas...


Solution

  • From the man page:

    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.

    So you need to declare a character array:

    char filename[] = "fileXXXXXX";
    mkstemp(filename);