Segmentation fault reversing a string literal [duplicate]
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
//char s[6] = {'h','e','l','l','o','\0'};
char *s = "hello";
int i=0,m;
char temp;
int n = strlen(s);
//s[n] = '\0';
while (i<(n/2))
{
temp = *(s+i); //uses the null character as the temporary storage.
*(s+i) = *(s+n-i-1);
*(s+n-i-1) = temp;
i++;
}
printf("rev string = %s\n",s);
system("PAUSE");
return 0;
}
On the compilation the error is segmentation fault (access violation). Please tell what is the difference between the two definitions:
char s[6] = {'h','e','l','l','o','\0'};
char *s = "hello";
Your code attempts to modify a string literal which is not allowed in C or C++ If you change:
char *s = "hello";
to:
char s[] = "hello";
then you are modifying the contents of the array, into which the literal has been copied (equivalent to initialising the array with individual characters), which is OK.
If you do char s[6] = {'h','e','l','l','o','\0'};
you put 6 char
s into an array on the stack. When you do char *s = "hello";
there's only a pointer on the stack and the memory that it points to may be read only. Writing to that memory causes undefined behavior.