-
Reverse a string
I am trying to write a program to reverse a string passed from main() to another function, but am getting segmentation fault (most likely on line #32). Could you please point out my mistake?
Thanks.
Code:
1 #include <stdio.h>
2 #include <string.h>
3
4 void reverse_string(char*, int start, int end);
5
6 int main()
7 {
8 char *str = "This is a Test String";
9
10
11
12 reverse_string(str, 0, strlen(str)-1);
13
14 printf("str after reverse = %s\n",str);
15
16 return 0;
17 }
18
19 void reverse_string(char* str, int start, int end)
20 {
21 int i,j;
22 char temp_ch;
23 printf("entering reverse_string\n");
24 printf("str = %s\n",str);
25
26
27
28 for(i=start,j=end; i<=end/2; i++,j--)
29 {
30 printf("i = %d\n",i);
31 temp_ch = str[i];
32 str[i] = str[j];
33 str[j] = temp_ch;
34 }
35
36 return ;
37 }
-
When you say
Code:
8 char *str = "This is a Test String";
you're declaring a pointer to a string literal, which itself resides in read-only memory. Good compilers will warn you about this if you enable warnings (e.g., "-W -Wall" with gcc). If you said
Code:
8 char str[] = "This is a Test String";
instead, that would declare an array with just enough space to hold the string (including the NULL terminator), and the array would be initialized with that data. This is what you want.
You see, you were trying to modify the read-only memory that the string literal is stored in: -- a sure way to get a segmentation fault. :)