1

Im trying to reverse a string in place.

void reverseStr(char *str)
{
 int i;
 int length;
 int last_pos;
 length = strlen(str);
 last_pos = length-1;

 for(i = 0; i < length / 2; i++)
 {
   char tmp = str[i];
   str[i] = str[last_pos - i];
   str[last_pos - i] = tmp;
 }
}

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400893 in reverseStr (str=0x400974 "Haus") at main.c:102
102         str[i] = str[last_pos - i];
(gdb) print i
$1 = 0
(gdb) print last_pos
$2 = 3
(gdb) print str
$3 = 0x400974 "Haus"
(gdb) print str[3]
$4 = 115 's'

Thank you for reading. I dont get it, how can this instruction cause an error? Regards :)

Zackline
  • 804
  • 1
  • 9
  • 28
  • this question has been asked plenty of times already: http://stackoverflow.com/questions/11538381/reverse-strings-in-c – Cacho Santa Mar 20 '13 at 20:01
  • @cacho: That question asks about an entirely different problem (with code that just happens to want to accomplish the same task, but in a different way). The other question's code is not reversing in-place, the error is different...basically, the solution given there is totally irrelevant here. – cHao Mar 20 '13 at 20:04
  • True, but my problem was the string literal, I could not find that out with your link. – Zackline Mar 20 '13 at 20:08
  • Although... [In-Place String Reverse in C](http://stackoverflow.com/questions/4785967/in-place-string-reverse-in-c) – cHao Mar 20 '13 at 20:14
  • Sorry, I will try to search better next time. – Zackline Mar 20 '13 at 20:34

3 Answers3

5

The code in reverseStr is fine, the problem is in the calling code. You almost certainly are passing a string literal or some other read-only memory to the function.

Most likely your calling code is:

char *str = "my string";//str points to a literal which cannot be modified
reverseStr(str);

But you need to pass writeable memory. Like this:

char str[] = "my string";
reverseStr(str);
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
1

You are passing a string literal to your function. String literals are non modifiable in C.

char *p = "this string is non modifiable";
reverseStr(p); // undefined behavior

Use an array initialized by a string instead:

char p[] = "this string is modifiable";
reverseStr(p); // OK
ouah
  • 142,963
  • 15
  • 272
  • 331
0

It depends on how you are calling this function.

  • If you're passing an address of a string constant (definition of type {char *str = "String"} are called as string constants. Ans string constants are put into .rodata section in executable file), then you'll receive exception.
  • If you're passing an address of array, (char arr[] = "String"), then the function will work.
jai.maruthi
  • 157
  • 5