Simple program segment faulting

I have the following simple C program giving segmentation fault and for the life of me I cannot see why.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
    {
    char *ptr;
    char KeepFn[80]; 
    printf("%d", __LINE__);
    ptr = mktemp("x_XXXXXX");
    printf("%d", __LINE__);
    sprintf(KeepFn, "%-.30s.XML", ptr);
    printf("%d", __LINE__);
    printf("%s",KeepFn);
    return(0);
    }

Please tell me what I have done wrong.
The mktemp() function replaces the contents of the string pointed
http://pubs.opengroup.org/onlinepubs/007908799/xsh/mktemp.html

You're passing in a const char *, that "x_XXXXXX" thing.
Doing :-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
    {
    char *ptr;
    char KeepFn[80];
    char *MyTemplate = "x_XXXXXX"; 
    ptr = (char *)mktemp(MyTemplate);
    sprintf(KeepFn, "%-.30s.XML", ptr);
    printf("%d", __LINE__);
    printf("%s",KeepFn);
    return(0);
    }


makes no difference. Am I still missing the point?
You have to pass in a writable buffer to mktemp.
1
2
3
4
5
6
7
8
9
10
11
#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    char tmpl[] = "x_XXXXXX"; 
    mktemp(tmpl);
    printf("%-.30s.XML\n", tmpl);

    return 0;
}
Last edited on
Thank you.
Topic archived. No new replies allowed.