0

Hi I wrote this code and the aim is to see weather a word is palyndrom or not, I get a segmenation fault while executing, may you help? Is it a good way to see if a word is palyndrom? thx in advance

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int m=1;

void palindromi();

int main (int argc, char *argv[]) {

    int len, a, i=0;

    if (argc != 2)
        exit(0);

    len = strlen(argv[1]);
    a = len-1;
    printf("La lunghezza della parola e' %d\n",len);

    palindromi(argv[1], len, a, i);

    return 0;
}

void palindromi(char *parola, int len, int a, int i) {

    if (i < len/2){
        if (parola[i] == parola[a]) {
            palindromi(parola, len, a--, i++);
        }
        else
            m = 0;
    }

    if (m == 1)
        printf("La parola e' palindroma\n");
    if (m == 0)
        printf("La parola non e' palindroma\n");
}
zmag
  • 7,825
  • 12
  • 32
  • 42
yepitis
  • 23
  • 4
  • Do you need it to be recursive? You could just use a while instead of your if... – B. Go Jan 14 '20 at 22:58
  • You're missing returns in palindromi to have a really useful function. Or would if you were not using a global variable, which you shouldn't do... – B. Go Jan 14 '20 at 23:02
  • from https://stackoverflow.com/questions/2989704/order-of-operations-for-pre-increment-and-post-increment-in-a-function-argument it appears you should call palindromi with --a and ++i, and here you have an infinite loop. Easy to check with a printf of these 2 values at the beginning of the function! – B. Go Jan 14 '20 at 23:08
  • Hi thx for the follow-up yes the problem was that i wrote a-- and i++, now is fixed thx – yepitis Jan 15 '20 at 00:24

1 Answers1

1

As stated in Order of operations for pre-increment and post-increment in a function argument?, post increment and decrement are done after the function call.
In your case, palindromi(parola, len, a--, i++); is the same as calling forever palindromi(parola, len, a, i); which is an infinite loop.
It should have been palindromi(parola, len, --a, ++i);, correctly changing the value before the recursive call.

B. Go
  • 1,436
  • 4
  • 15
  • 22