Search code examples
cstringstrrchr

segmentation fault in use of strrchr function


Here is my program which reverses a string. I am trying to use function strrchr at the end because I am entering the string James Bond on standard input. So I want to see if strrchr function gives a pointer to value character B of the above string.

#include<stdio.h>
#include<string.h>
int main ()
{
    char rt[100];
    char temp,*op;

    printf("enter a string\n");
    scanf("%s",rt);

    printf("the string you entered is %s\n",rt);

    int i, k, length;
    i=0;
    k=strlen(rt);

    printf("strlen gives =%d\n",k);

    length=k;
    length--;

    for(;i<k/2;i++)
    {
        temp=rt[i];
        rt[i]=rt[length-i];
        rt[length-i]=temp;
    }

    printf("the reverse string is %s\n",rt);

    op=strrchr(rt,'B');
    printf("strrchr gives %c\n",*op);
}

Now when I run above I get

./a.out 
enter a string
James Bond
the string you entered is James
strlen gives =5
the reverse string is semaJ
Segmentation fault

What can be the reason for this. Is above use of strrchr wrong?


Solution

  • Try this:

    #include<stdio.h>
    #include<string.h>
    int main ()
    {
        char rt[100];
        char temp,*op;
        printf("enter a string\n");
        fgets(rt, 100, stdin);
        printf("the string you entered is %s\n",rt);
        int i,k,length;
        i=0;k=strlen(rt);
        printf("strlen gives =%d\n",k);
        length=k;
        length--;
        for(;i<k/2;i++)
        {
            temp=rt[i];
            rt[i]=rt[length-i];
            rt[length-i]=temp;
        }
        printf("the reverse string is %s\n",rt);
        op=strrchr(rt,'B');
        printf("strrchr gives %c\n",*op);
        return 0;
    }
    

    scanf %s only takes non-white space chars. So James Bond is not completely read. fgets works well and should be preferred for user input.

    For more info regarding scanf, gets and fgets, see this.