void main() {
void strrev(char *);
char *p="GOOd";
strrev(p);
printf("%s",p);
}
void strrev(char *str) {
char temp, *end_ptr;
if( str == NULL || !(*str) ) return;
end_ptr = str + strlen(str) - 1;
while( end_ptr > str )
{
temp = *str;
*str = *end_ptr;
*end_ptr = temp; str++;
end_ptr--;
}
}
i am getting the error segmentation failed can any one help me out how to sort it out...
The statement:
char *p = "GOOd";
Defines a string literal "GOOD", pointed by an pointer p
.
You are trying to modify this string literal through the strrev
function which results in Undefined Behavior(UB) and the crash.
The problem with string literals is they are stored in a read-only(Implementation defined) memory location and user programs are not allowed to change that.If a program attempts to do so it causes an UB.
So instead of using a string literal You should use an array.
You should be using:
char p[] = "GOOd";
One problem is that in the following:
char *p = "GOOd";
the compiler is allowed to place the string literal in read-only memory.
Any attempt to modify the string pointed to by p
results in undefined behaviour.
Try changing the above line to:
char p[] = "GOOd";
I don't see anything wrong with the strrev()
function itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With