Just for fun I have written a function to check if string given is palindrome. When I run the prog it throws segmentation fault. Could anyone please throw light on it.
int palindrome( const char *input )
{
char * reverse;
int len = 0 ;
int i = 0;
bool result = false;
len = strlen(input);
if( len <= 1)
return -1;
reverse = (char *)malloc( sizeof ( char)* len);
printf( " the len of character is %d", len);
while( input[i++] != '/0')
{
reverse[ --len] = input[i];
}
reverse[len] = '/0';
printf(" the reverse string is %s", reverse);
if( !strcmp( input, reverse) )
return 1;
else
return 0;
}
Thanks
Sam
Changing the code as per suggestions to:
int palindrome( const char *input )
{
char * reverse;
int len = 0 ;
int i = 0;
bool result = false;
len = strlen(input)+1;
if( len <= 2)
return -1;
reverse = (char *)malloc(len);
printf( " the len of character is %d", len);
reverse[len] = '\0' ;
while( input[i++] != '\0')
{
reverse[ --len] = input[i];
}
printf(" the reverse string is %s", reverse);
if( !strcmp( input, reverse) )
return 1;
else
return 0;
}
I still have a problem. The segmentation fault has disappeared but the reversed string is empty.
A few points:
'\0', not'/0'.sizeof(char)is always 1, you don’t need to multiply by it.strlen(s) + 1.mallocin C, it hides certain errors that you would be better off knowing about.lento populate the reverse string, it will end up as 0, not usable for placing the null terminator at the end of that string. This is probably the immediate cause of your core dump since callingstrcmpon a non-null-terminated string is a bad idea.On that last point, what I mean is something like (pseudo-code):
And, with the update, you have the right idea, setting the null terminator fist before reducing
len.But since,
lenis now the string length plus one, you’re populating indexes 1 thru LEN rather than 0 thru LEN-1.Change:
to:
Or, better yet, change it so that
lenis still the length of the string (forprintf):to: