0

Here is the way how I can display the string "dcba":

main()
{
    char s[10] = "abcd";
    puts(strrev(s));
}

The way how I get a "Segmentation Fault" (why?):

puts(strrev("abcd"));

And here is the function that reverse the string:

char *strrev(char *s)
{
    int i, j;
    char aux;

    for(i=0, j=strlen(s)-1; i<j; i++, j--)
    {
        aux = s[j];
        s[j] = s[i];
        s[i] = aux;
    }

    return s;
}
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
Ricardo
  • 67
  • 8
  • A string literal is constant. – limits Jul 05 '16 at 02:49
  • 1
    Careful, @overtheboard. While you are wise to *treat* literals as if they were constant, that word has a specific meaning in the standard. They are not *required* to be unchangable and, in fact, phase 6 creates an array of `char` rather than `const char`. I'm sure you meant the former but I'm feeling unwisely pedantic today :-) – paxdiablo Jul 05 '16 at 03:23
  • This code works for me.. – Twinkle Jul 05 '16 at 06:47
  • 1
    @Twinkle, sometime, undefined behaviour works (on some implementations, under certain circumstances, when compiled with certain flags and run on any day other than one following a blue moon). That is its most insidious property :-) – paxdiablo Jul 05 '16 at 06:55

1 Answers1

4

In C, it's because trying to modify a string literal is one of the things that's considered undefined behaviour.

The reason literal string modification was marked as undefined behaviour in the original C standard (keeping in mind that the original intent of the ANSI/ISO C standards bodies was to codify existing practice rather than invent a new language) was because some implementations in existence at the time stored string literals in read-only memory, or shared identical string literals to reduce memory usage.

And, since each iteration of the standard after that point valued backward compatibility (and some implementations may still optimise for space or protect string literals from inadvertent corruption), there's been no real desire to change it.

Bottom line, undefined behaviour is generally bad, don't do it.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • AFAIK, not just pre-standards. It is still done that way these days. – Rudy Velthuis Jul 05 '16 at 02:52
  • @Rudy, apologies, I didn't mean to suggest it wasn't done that way today, just that, because it was done that way before C89/90, they had to honour it. I'll try to change the answer to clarify. – paxdiablo Jul 05 '16 at 03:13
  • no need to apologize. But literals are often still in read-only memory. Hence the segfault. – Rudy Velthuis Jul 05 '16 at 06:21