Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get a segmentation fault with isdigit()?

Tags:

c

Scenario 1: Code:

int main(){
    int a = 12345678;

    if(isdigit(a)){
        printf("ok: foo\n");
    }
    else{
        printf("false: bar\n");
    }
    printf("test\n");

    return EXIT_SUCCESS;
}

Output:

Segmentation fault

Scenario 2: Code:

 ...
    if(isdigit(a)){
        //printf("ok: foo\n");
    }
    else{
        //printf("false: bar\n");
    }
    printf("test\n");
 ...

Output:

test

and now the last, Code:

...
int a = 1234567;
...

Output:

ok: foo
test

What's wrong with isdigit()? I do not understand!

like image 263
krzym Avatar asked Dec 03 '25 16:12

krzym


2 Answers

Probably because the compiler optimizes the isdigit function call from the code. That is it doesn't run it.

Also note that isdigit expects a character, not a number. http://www.cplusplus.com/reference/clibrary/cctype/isdigit/

like image 144
Karlth Avatar answered Dec 05 '25 07:12

Karlth


This is because isdigit can be defined as macro like this

#define isdigit(c) ((map[c] & FLAG_DIGIT)==FLAG_DIGIT)

You call isdigit with integer value, but map array size is 256 elements. In this case you try to read value outside of array bounds -> segmentation fault. This segmentation fault can occurs randomly. Depending on your program or data size.

like image 27
vromanov Avatar answered Dec 05 '25 08:12

vromanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!