Error : segmentation fault , core dumped , in c programming

Error : segmentation fault , core dumped , in c programming

以下 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]='[=10=]';
    
    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]='[=10=]';
    
    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;
}

既然已经生成了core dump,你可以自己搞定:

> 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++) 中的 <=,否则您将替换尾随的 NUL字符 ('[=14=]') 与 's' 并且您最终访问数组边界之外。