Search code examples
csumtermination

C beginner not terminating program


I'm a beginner in C and I received the task to write a simple sum program, where I have to use my own atoi function.

The behavior is really strange:
sum 1 -> works fine, it writes "the sum is 1"
sum 1 2 -> it doesn't terminate
sum -1 -2 -> it only writes the first number, if I use more than 2 it doesn't terminate

This are some parts of the code, I suppose that the error is in the mi_atoi, cause it works normally if I use the library function:

unsigned int char2int(char c)
{
    return c-'0';
}

int mi_atoi(char *s)
{
    int x = 0;
    if (s[0] == 45) {
        for (i = 1; s[i] != '\0'; i++) {
            x = x*10 - char2int(s[i]);
        }
    }
    else { 
        for (i = 0; s[i] != '\0'; i++) {
            x = x*10 + char2int(s[i]);
        }
    }

    return x;
}

And here the main (the function esNumero just checks if the argument is a number and it works fine):

int main (int argc, char *argv[])
{
    char buf[80];
    int suma = 0;

    for (i = 1; i < argc; i++) {
        if (esNumero (argv[i]) == 0) {
            sprintf (buf, "El parametro \"%s\" no es un numero\n", argv[i]);
            write (1, buf, strlen (buf));
            return 0;
        }
        else {
            suma = suma + mi_atoi(argv[i]);
        }
    }
    sprintf (buf, "La suma es %d\n", suma);
    write (1, buf, strlen (buf));

    return 0;
}

Could you please have a look at my code and tell me what I'm doing wrong?


Solution

  • Your i is a global variable and therefore shared between main and mi_atoi. Every time you call mi_atoi, it resets i, so the loop in main never terminates.

    You cleverly tried to hide the bug by not posting the declaration of i (let alone a Minimal, Complete, and Verifiable Example), but we can see that i is not declared as a local variable in the functions you did post.