1

I am trying to remove two consecutive duplicate elements from the string.I am getting segmentation fault in the line 16 .even the commented 17th line also get me the same error.

dont worry about my logic of my program.it may be wrong...but i am struck with this error..help me out...explain why i am getting this error

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *st="fvvbbyyr";
    int i=0,j,len;
    for(len=0;st[len]!='\0';len++);
    for(i=0;i<len;i++)
    {
        if(st[i]==st[i+1])
        {
            for(j=i+2;j<len;j++)
               {
                   *(st+j-2)=*(st+j);
                   //st[j-2]=st[j];
               }
            len = len-2;
            i=-1;
        }
    }
    return 0;
}
karthik
  • 463
  • 1
  • 6
  • 16

1 Answers1

4
char *st = "fvvbbyyr";

st points to the anonymous string "fvvbbyyr", which can be located in read-only memory.

*(st+j-2) = *(st+j);

Attempting to modify such value leads to an undefined behavior.

A good habit is to declare the pointer as const char * because a string litteral behaves in this way.

const char *st = "fvvbbyyr";

Then your compiler should print some warnings/errors. Use rather an array:

char st[] = "fvvbbyyr";

BTW, the array subscripting operator [] may make your code more readable.

st[j - 2] = st[j];

Moreover you are accessing to st[i+1] == st[len] once in your loop.

md5
  • 23,373
  • 3
  • 44
  • 93