在代码第51行“(*str) = (*next)”处报错:Program received signal SIGSEGV, Segmentation fault
描述如下:
编写一个函数,删除一个字符串的一部分。函数原型如下:
int del_substr (char *str, char const *substr)
举个例子,假定str指向ABCDEFG. 如果substr指向FGH, CDF或XABC, 函数应该返回0,str未做任何修改。但如果substr指向CDE, 函数就把str修改为指向ABFG.
代码实现如下:
#include#include/*
** If the string "substr" appears in "str", delete it.
*/
//#define NULL 0 /* null pointer */
//#define NUL ’\0’ /* null byte */
#define TRUE 1
#define FALSE 0
/*
** See if the substring beginning at ’str’ matches the string ’want’. If
** so, return a pointer to the first character in ’str’ after the match.
*/
char *match (char *str, char const *want)
{
while (*want != '\0') {
if (*str++ != *want++) {
return NULL;
}
}
return str;
}
int del_substr (char *str, char const *substr)
{
char *next = NULL;
char *res = str;
/*
** Look through the string for the first occurrence of the substring.
*/
while( *str != '\0' ){
next = match( str, substr );
if( next != NULL )
break;
str++;
}
printf("##next: %s\n", next);
printf("##str: %s\n", str);
/*
** If we reached the end of the string, then the substring was not
** found.
*/
if( *str == '\0' )
return FALSE;
/*
** Delete the substring by copying the bytes after it over the bytes of
** the substring itself.
*/
while(*next != '\0'){
(*str) = (*next);
printf("##str: %s\n", str);
printf("##next: %s\n", next);
str++;
next++;
}
*str = '\0';
printf("after del_substr result: %s\n", res);
return TRUE;
}
int main()
{
char *str = "ABCDEFG";
char const *sub_str1 = "FGH";
char const *sub_str2 = "DE";
int res = -1;
res = del_substr(str, sub_str2);
// printf("the resust is %s\n", str);
printf("the res is %d\n", res);
return res;
}
报错如下:
38 printf("##next: %s\n", next);
(gdb)
##next: FG
39 printf("##str: %s\n", str);
(gdb)
##str: DEFG
44 if( *str == '\0' )
(gdb)
50 while(*next != '\0'){
(gdb)
51 (*str) = (*next);
(gdb)
Program received signal SIGSEGV, Segmentation fault.
0x0804849f in del_substr (str=0x8048667 "DEFG", substr=0x8048670 "DE")
at del_substr.c:51
51 (*str) = (*next);
(gdb)
--------------------------------分割线--------------------------------
知道问题出在哪里了
main函数最开始的变量初始化
char *str = "ABCDEFG";
str指向的是只读常量区,所以执行到(*str) = (*next);会报错,该语句试图改变只读常量区里的值时,操作系统向程序发送了一个信号,告诉程序操作系统检测到了非法的内存访问,为了防止内存空间被破坏,操作系统提前终止了该程序的运行;
用数组声明即可
char str[] = "ABCDEFG";