-3

When I run this code, I am getting segmentation fault. How can I fix it?

#include <stdio.h>

void reverse(char *str)
{
    char *end=str;
    char temp;
    while(*end)
    {
    ++end;
    }
    --end;

    while(str < end)
    {
        temp=*str;
        *str=*end;
        *end=temp;
        str++;
        end--;
    }
}

void main()
{
    char *s="random";
    reverse(s);
}
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
S-N
  • 1
  • 1
  • 2
    It is probably a good idea to learn a debugger, such that you master those kind of problems on your own. – Micha Wiedenmann Mar 22 '15 at 18:16
  • 1
    Numerous duplicates, e.g. [Why is this string reversal C code causing a segmentation fault?](http://stackoverflow.com/questions/1614723/why-is-this-string-reversal-c-code-causing-a-segmentation-fault) and [Segmentation fault reversing a string literal](http://stackoverflow.com/questions/3172075/segmentation-fault-reversing-a-string-literal) – Paul R Mar 22 '15 at 18:17

1 Answers1

1

You are trying to reverse constant value. Now that's not possible. Because you are trying to change a portion of read-only memory.

Solution: Just use char s[]="random";

Previous case: s is pointing to the constant "random".

In this case: s is pointing to a local copy of the string literal "random" which is in stack memory.

user2736738
  • 30,591
  • 5
  • 42
  • 56