1

I am trying to reverse a string literal with the use of pointers, though my code received SEGSIGV signal on *head=*tail line

char* reverse(char* input, int n) {
    char temp;
    char* head= input;
    char* tail= &input[n-1];
    while(head<tail){
        temp=*head;
        *head=*tail;
        *tail=temp;
        head++;
        tail--;
    }
    return input;
}


int main(void){
    char* sentence= "All work and no play makes jack a dull boy";
    reverse(sentence, strlen(sentence));
    printf("%s", sentence);
    return 0;
}

I don't know if I am trying to access restricted memory segment.

Mosaaleb
  • 1,028
  • 1
  • 9
  • 23
  • 2
    string literals might not be writeable, and writing to them gives undefined behaviour. You need to either use a `char` array instead, or write the reversed string to a different location (that's writeable). – Dmitri Apr 11 '17 at 15:28
  • String literals are usually read-only and any attempt to modify one leads to undefined behaviour and usually a crash. Don't do it! – Jonathan Leffler Apr 11 '17 at 15:29

1 Answers1

2

Yes, you are trying to modify read-only memory.
You cannot rearrange a constant string.

With a simple change you can fix it:

char sentence[] = "All work and no play makes jack a dull boy";

(use an array instead of a pointer)

abelenky
  • 63,815
  • 23
  • 109
  • 159