Reverse a string in C solution segfaulting

北战南征 提交于 2020-01-14 09:22:26

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/5220206/reverse-a-string-in-c-solution-segfaulting

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