错误:分段错误,核心转储,在c编程



下面的c编程代码给出了一个核心转储分割错误,请告诉我为什么我得到这个错误,并帮助我给这个代码的更正版本。谢谢!

#include <stdio.h>
#include <string.h>

int main()
{
char str[100], ch;
int i, Flag;
Flag = 0;

printf("n Please Enter any String :  ");
fgets(str,sizeof(str),stdin);
printf("%s",str);
printf("n Please Enter the Character that you want to replace with :  ");
scanf("%c", &ch);

for(i = 0; i <= strlen(str); i++)
{
str[i]=ch;    
}
str[i]='';

printf("n The characters have been found and replaced with %c and they occur %d times ", ch, i + 1);
printf("The replaced string is %s ",str);

return 0;
}

试试这个

#include <stdio.h>
#include <string.h>

int main()
{
char str[100], ch;
int i, Flag;
Flag = 0;

printf("n Please Enter any String :  ");
fgets(str,sizeof(str),stdin);
printf("%s",str);
printf("n Please Enter the Character that you want to replace with :  ");
scanf("%c", &ch);

for(i = 0; i < strlen(str); i++) //change <= to < 
{
str[i]=ch;      
}
str[i]='';

printf("n The characters have been found and replaced with %c and they occur %d times ", ch, i + 1);
//printf("The replaced string is %s ",str);

return 0;
}

既然已经生成了核心转储,您可以自己计算:

> ulimit -c unlimited
> gcc -g -o demo demo.c
> ./demo
> ...
> Segmentation fault (Core dumped)
> gdb demo core
(gdb) run
Starting program: /home/david/demo 
Please Enter any String :  bla bla
Please Enter the Character that you want to replace with :  s
Program received signal SIGSEGV, Segmentation fault.
(gdb) where
#0  __strlen_avx2 () at ../sysdeps/x86_64/multiarch/strlen-avx2.S:181
#1  0x000055555555529a in main () at demo.c:16
(gdb) bt full
str = 's' <repeated 100 times>

在调试器的帮助下,您可以看到错误在第16行。您希望<而不是<=for(i = 0; i <= strlen(str); i++)中,否则您将用's'替换末尾的NUL字符(''),并且最终访问数组的边界之外。

最新更新