do not try to modified the value in const region

  I run into this troublesome in the morning , I realize how foolish I did suddenly , as you the title says, "do not try to modified the value in const region".

I write a funciton to reverse a string , fortunately I give a string array to it's argment firstly, it ok,

however it's show "segmentation fault", when I try to give string to it by a point:

 

/* strrev.c by vinco at 2011-08-04
   Ubuntu9.10 CC/GCC
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char* strrev(char* str);

int main()
{
#if 0
	char* str = "vinco zhang";
	//char* p ="vinco zhang";
	//char* str = (char*) malloc(32);
	//strcpy(str,p);
#else
	char str[]="vinco zhang";
#endif
	//strrev(str);
	//printf("strrev : str = %s\n",str);

	printf("strrev : str = %s\n", strrev(str) );

	return 0;
}

char* strrev(char* str)
{
	char* p = str;
	char t;
	int i=0, len = strlen(str) - 1;

	for(i=0 ; i<len ; i++, len--)
	{
		t = *(p+i) ;
		*(p+i) =  *(p+len) ;
		*(p+len) = t ;
	}
	return str;
}

1. case #if 0, I give a string array to strrev(), it work well:

root@vinco:/home/vinco# make strrev
cc     strrev.c   -o strrev
root@vinco:/home/vinco# ./strrev
strrev : str = gnahz ocniv
root@vinco:/home/vinco# 

2. case #if 1,"segmentation fault"

root@vinco:/home/vinco# make strrev
cc     strrev.c   -o strrev
root@vinco:/home/vinco# ./strrev 
Segmentation fault

3, to void the problem, as you see:

   i. do as case #if 0

   ii. so as the comment :( it's just a liite troublesome , but it done)

        char* p ="vinco zhang";
        char* str = (char*) malloc(32);
        strcpy(str,p);

Summary:

1.do not try to modified the value in const region ;

2.the funciton should be declarated as following  format if you would not modified it's argment :

   char*/void funcion(const char* s1 ,const char* s2,.... )

3. if you have to give it to a string to the argment of a function , do as case "#if 0" or the comment I show above

你可能感兴趣的:(function,String,ubuntu)