Skip to content

Instantly share code, notes, and snippets.

Last active August 29, 2015 14:22
What would you like to do?
#include "apue.h"
#include <errno.h>
void make_temp(char *template);
char good_template[] = "/tmp/dirXXXXXX"; /* right way */
char *bad_template = "/tmp/dirXXXXXX"; /* wrong way*/
printf("trying to create first temp file...\n");
printf("trying to create second temp file...\n");
make_temp(char *template)
int fd;
struct stat sbuf;
if ((fd = mkstemp(template)) < 0)
err_sys("can't create temp file");
printf("temp name = %s\n", template);
if (stat(template, &sbuf) < 0) {
if (errno == ENOENT)
printf("file doesn't exist\n");
err_sys("stat failed");
} else {
printf("file exists\n");
If we execute this program, we get
$ ./a.out
trying to create first temp file...
temp name = /tmp/dirUmBT7h
file exists
trying to create second temp file...
Segmentation fault
The difference in behavior comes from the way the two template strings are
declared. For the first template, the name is allocated on the stack, because we use an
array variable. For the second name, however, we use a pointer. In this case, only the
memory for the pointer itself resides on the stack; the compiler arranges for the string to
be stored in the read-only segment of the executable. When the mkstemp function tries
to modify the string, a segmentation fault occurs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment