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.
With some versions of gcc you can allow modification of static strings with -fwritable-strings. Not that there is really any good excuse to do that.
You can try this:
void strrev(char *in, char *out, int len){
int i;
for(i = 0; i < len; i++){
out[len - i - 1] = in[i];
}
}
Note that it doesn't deal with the string terminator.
精彩评论