-1

I have been trying to remove characters from a string without using extra memory and soing it in place. I just tried removing character 'a' from a given input string but my code gives a segmentation fault .

Input- abca

Output-bc Debugger says the segmentation error is in line "str[j]=str[i]". Please help me out :) Thanks

Here is the code

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

void removest(char *str) 
{
  int i,j=0;
  int len=strlen(str);
  for(i=0;i<len;i++)
    {
       if(str[i]=='a')
    {
      i=i+1;
    }
      str[j]=str[i];
      j++;
    }
  str[j]='\0';
  printf("%s \n",str);
}

int main()
{
  char *str="abca";
  removest(str);
}
user2456752
  • 85
  • 1
  • 4
  • 12

2 Answers2

2

char *str = "abca"; is wrong as str pointer to string literal. Use char array, it should be char str[] = "abca";.

Because str points to a const string literal and so an expression like str[i] = 'F' is an illegal expression (because it tries to modify the first character of a constant string), which causes Undefined behavior at runtime.

There are also one bug in your logic as well. It is not logically correct to increment i again inside the for loop with i as variable. It should be coded as below.

for(i=0; i<len; i++)
{
    if(str[i] == 'a')
    {
        continue;
    }
    str[j] = str[i];
    j++;
}
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
user1969104
  • 2,340
  • 14
  • 15
0

Output-bc Debugger says the segmentation error is in line "str[j]=str[i]".

in this part of code

if(str[i]=='a')
{
  i=i+1;
}
  str[j]=str[i];

when i value will len-1;

then it is incremented now str[i] goes out of bound than str size which will be error.

InvisibleWolf
  • 917
  • 1
  • 9
  • 22