-3

I tried to run this program in Visual stdio and used WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB as input. After running it, it's showing Segmentation fault (core dumped).

How to solve this?

#include <stdio.h>
#include <string.h>
int main()
{
    char string[201];
    int i, j;
    scanf("%s",string);

    for(i=0;i<strlen(string); i++){
        if(string[i]=='W' && string[i+1]=='U' && string[i+2]=='B'){
            for(int k=i; k<i+3; k++){
                string[k]='o';
                i=i+2;
            }
        }
    }
    puts (string);

}

I want to know whats wrong with my program here

  • No. I want to know what's wrong with my program here. –  May 08 '21 at 15:07
  • 2
    @PronaySarker You are iterating over your string in a wrong way. Just run your code in debug mode and see what's wrong. I think it's your if statement. – Shambhav May 08 '21 at 15:40
  • It seems your question was closed because the title ask for a question that is already answered. But actually, you really want to know what in your code is causing the segmentation fault. It is probably a good idea to have your question title reflect what you really want! Think about it for your next question. – fpiette May 09 '21 at 06:27

1 Answers1

0

You cannot access string[i+2] when I is equal to strlen(string) - 1. You can access string[i+1] which will be the terminating nul char.

Change the upper limit of you for loop.

fpiette
  • 11,983
  • 1
  • 24
  • 46