Search code examples
csegmentation-faultpalindrome

Why am I getting a 'Segmentation Fault' error in my code?


I have this code to check for a palindrome in C:

#include <stdio.h>

int main(void) {
    char* test="racecar";
    Palindrome(test, 7);
}

int Palindrome(char mystr[], int len){
    if(len<2)
        printf("Palindrome");
    else if (mystr[0]==mystr[len-1]){
        char* newstr;
        int i=0;
        int j=1;
        while(j<len-1){
            newstr[i]=mystr[j];
            i++;
            j++;
        }
        printf("%s", newstr);
        return Palindrome(newstr, len-2);
    }
    else
        printf("Not palindrome");
}

But I am getting this error: Segmentation fault (core dumped)

Why is this?


Solution

    1. char *newstr is uninitialized which cause your segfault when you deference it.
    2. return an int when you declare the function as such.
    3. (advise) It's a good idea to terminate lines with a \n.

    The way you structured your code I thought you were going for a recursive algorithm:

    #include <stdio.h>
    #include <string.h>
    
    int Palindrome(char mystr[], size_t len) {
        if(len < 2) {
            printf("Palindrome\n");
            return 1;
        }
        if(mystr[0] != mystr[len-1])
            printf("Not palindrome\n");
            return 0;
        }
        return Palindrome(mystr + 1, len - 2);
    }
    
    int main(void) {
        char *test = "racecar";
        Palindrome(test, strlen(test));
    }
    

    and the corresponding output is:

    Palindrome
    

    Here is how I would write the iterative version:

    int Palindrome(char mystr[], int len){
        for(; len > 1; mystr++, len -= 2) {
            if(*mystr != mystr[len - 1]) {
                printf("Not palindrome\n");
                return 0;
            }
        }
        printf("Palindrome\n");
        return 1;
    }