1
#include <stdio.h>

void reverse(char *str){
    char * end = str;
    char tmp;
    if (str){
        while(*end){
            ++end;
        }
        --end;
        while (str < end){
            tmp = *str;
            *str++ = *end; // segmentation error
            *end-- = tmp;
        }
    }
}
  int main() 
  {
    char *name = "erogol"
    reverse(name);
    //printf("%s\n", name );

    return 0;  
  } 

Why do you think segmentation error occurs at the place I singed with comment?

erogol
  • 12,388
  • 30
  • 95
  • 151

2 Answers2

2

Because name (as string literal) is for read only.

Use

char name[] = "erogol";

Seems that you are using a debugger, consider also using valgrind (sometimes it gives more details):

==4040== Process terminating with default action of signal 11 (SIGSEGV)
==4040==  Bad permissions for mapped region at address 0x40065C
==4040==    at 0x400551: reverse (demo.c:16)
==4040==    by 0x40058E: main (demo.c:24)
David Ranieri
  • 37,819
  • 6
  • 48
  • 88
1

Because you modify a string literal.

Even though their type is char[] and not char const[] you don't have the right to modify them.

Jens Gustedt
  • 74,635
  • 5
  • 99
  • 170