for my recover.c i have trouble changing the filenames. I get a segmentation fault probably because of incorrect usage of sprintf.

Code looks sort of like this:

    // pseudocode for testing sprintf change filename

    char* outfile = "000.jpg";
    printf ("%s", outfile);
    int start = 3;
    sprintf (outfile, "O%d.JPG", start);
    printf ("%s", outfile);


Can anybody help?

2 Answers 2


String literals (e.g., 000.jpg) are constant expressions. They are read-only. When assigning a string literal to a variable of type char *, you get a memory address stored in that char * variable that points to a location on a data segment. Any attempt to change the contents of the string in such case results in a segmentation fault.

A quick fix to that may be declaring your outfile as a char [] instead. In this case, I think the compiler just copies the contents of your string literal into your char [] and ignores the string literal itself.


char* outfile = "000.jpg";

Actually your sprintf function looks good. I think this line is where the problem is. You've assigned outfile the address of a string literal, which will be automatically stored in a read-only portion of memory. Then your sprintf function tries to change it, your pc freaks out (because you're not allowed to touch it).

So you'll want to change how you create your outfile variable, if you want to leave it as a pointer, you should malloc some space instead, then probably use sprintf to populate it, or you could store it in a char array instead.

Hope that helps!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .