Reverse a string in c [duplicate]

巧了我就是萌 提交于 2019-12-13 02:30:52

问题


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 :)


回答1:


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);



回答2:


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



回答3:


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.


来源:https://stackoverflow.com/questions/15533493/reverse-a-string-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!