Search code examples
carraysstringgetchar

Segmentation failed (core dumped), C


I have the following programme:

#include <stdio.h>
#include <stdbool.h>

#define MAX 100
//a)
bool isPalyndrom(char c[], int cnt) {
    int i;
    char pal[MAX];
    int j = 0;
    for (i = cnt - 1; i >= 0; i++) {
        pal[j] = c[i];
        j++;
    }
    for (i = 0; i < cnt; i++) {
        if (c[i] != pal[i]) return false;
    }
    return true;
}

int main() {
    char c, s[MAX];
    int i = 0;
    int cnt = 0;
    do {
        c = getchar();
        s[i] = c;
        i++;
        cnt++;
        printf("\n%s\n", s);
    } while (c != '\n');
    printf("%d", cnt);
    bool istrue = isPalyndrom(s, cnt);
    if (istrue) {
        printf("\n%s Pal.\n", s);
    } else {
        printf("\n%s not Pal.\n", s);
    }
    return 0;
}

However, when I run it, is shown: segmentation fault, the problem is in the do-while loop, the programme stops, after my char c are written in the array and before the do-while loop is left. Could somebody take a look in the do-while loop?


Solution

  • There is a typo in this loop

    int j=0;
    for(i=cnt-1; i>=0; i++){
                       ^^^^
    pal[j]=c[i];
    j++;
    }
    

    I think you mean i--

    Also you did not assign the terminatinbg zero to array s So using for example this statement

    printf("\n%s\n",s);
    

    in this do-while loop

    do{
    c=getchar();
    s[i]=c;
    i++;
    cnt++;
    printf("\n%s\n",s);
    }while(c!='\n');
    

    is wrong.

    Besides you included the new line character in the array s.

    Take into account that the function can be written simpler without using an auxiliary array. For example

    bool isPalyndrom( const char s[], size_t n ) 
    {
        size_t i = 0;
    
        while ( i < n / 2 && s[i] == s[n-i-1] ) ++i;
    
        return i == n / 2;
    }