do not try to modified the value in const region

本文探讨了在C语言中使用字符串反转函数时遇到的问题,强调了修改const区域的值可能导致的错误,并提供了避免此类问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值