Reputation: 5371
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?
Upvotes: 1
Views: 1338
Reputation: 10415
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.
Upvotes: 2
Reputation: 434695
From the fine manual:
Upon successful completion, strrchr() shall return a pointer to the byte or a null pointer if c does not occur in the string.
Since there is no 'B'
in rt
when you call strrchr(rt, 'B')
, you get a NULL pointer back and then you try dereference it in your printf
call. Hence your segfault.
Upvotes: 1
Reputation: 43508
Before dereferencing op
with the *
unary operator, you have to check whether it's NULL
(this will be the case when the character is not found):
op = strrchr(rt, 'B');
if (op != NULL)
printf("strrchr gives %c\n", *op);
Upvotes: 4