开发者

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

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("t开发者_Go百科est\n");
 ...

Output:

test

and now the last, Code:

...
int a = 1234567;
...

Output:

ok: foo
test

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


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/


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.


This was probably optimized by the compiler. As neither the if or the else does something, it was removed and the isdigit ends up not called. Be sure to

#include <ctype.h>

The segmentation fault is coming probably from the fact that you're passing a (not so small) number, when a character was expected. When you remove the printf statements and the compiler optimizes it, the call won't happen thus not failing.

Note that the headers can be in fact omitted since the program will be linked with the standard C library by default, so it works. But it's not a good idea, and you should see a warning at least.


First of all, isdigit(3) checks whether a character is a digit.

The segmentation fault probably (I'm positive) happens because you haven't included stdio.h.

Then you're calling printf which uses variable arguments without knowing its prototype (undefined behavior).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜