Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a string in C solution segfaulting

I've come up with the following solution in C for reversing a string:

#include <stdio.h>

void reverse(char * head);

void main() {

  char * s = "sample text";
  reverse(s);
  printf("%s", s);
}

void reverse(char * head) {

  char * end = head;
  char tmp;

  if (!head || !(*head)) return;

  while(*end) ++end;

  --end;

  while (head < end) {
    tmp = *head;
    *head++ = *end;
    *end-- = tmp;
  }
}

However my solution is segfaulting. According to GDB, the offending line is the following:

*head++ = *end;

The line segfaults on the first iteration of the while loop. end points to the last character of the string "t" and head points to the beginning of the string. So why isn't this working?

like image 861
Sam Avatar asked Mar 07 '11 13:03

Sam


2 Answers

Change

char * s = "sample text";

To

char s[] = "sample text";

"sample text" is a string literal which may reside in a read-only section of your address space. Using the array syntax ensures this string is copied to stack, which is writable.

like image 78
Erik Avatar answered Sep 25 '22 23:09

Erik


Your s is pointing to a string literal:

char * s = "sample text";

In the function reverse you are trying to modify the string literal which results in undefined behavior.

To fix this make s a char array:

char s[] = "sample text";
like image 20
codaddict Avatar answered Sep 25 '22 23:09

codaddict