Segmentation error by reversing a string literal

#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+ni-1); *(s+ni-1) = temp; i++; } printf("rev string = %s\n",s); system("PAUSE"); return 0; } 

When compiling, an error is a segmentation error (access violation). Tell me the difference between the two definitions:

 char s[6] = {'h','e','l','l','o','\0'}; char *s = "hello"; 
+6
c
source share
4 answers

Your code is trying to modify a string literal that is not allowed in C or C ++. If you change:

 char *s = "hello"; 

in

 char s[] = "hello"; 

then you change the contents of the array into which the literal was copied (the equivalent of initializing the array with individual characters), which is fine.

+13
source share

If you do char s[6] = {'h','e','l','l','o','\0'}; , you put 6 char in an array on the stack. When you do char *s = "hello"; , only the pointer to the stack and the memory it points to can only be read. Writing to this memory causes undefined behavior.

+4
source share

On some versions of gcc, you can enable static string changes with -fwritable-strings. Not that there really was any excuse for this.

0
source share

You can try the following:

 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 is not related to the string terminator.

0
source share

All Articles