程序报错:Program received signal SIGSEGV, Segmentation fault

荣子3507 2017-11-30 11:24:45
在代码第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 <stdlib.h>
#include <stdio.h>

/*
** 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)
...全文
663 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
荣子3507 2017-12-01
  • 打赏
  • 举报
回复 1
知道问题出在哪里了 main函数最开始的变量初始化 char *str = "ABCDEFG"; str指向的是只读常量区,所以执行到(*str) = (*next);会报错,该语句试图改变只读常量区里的值时,操作系统向程序发送了一个信号,告诉程序操作系统检测到了非法的内存访问,为了防止内存空间被破坏,操作系统提前终止了该程序的运行; 用数组声明即可 char str[] = "ABCDEFG";

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧