简体   繁体   English

为什么我用isdigit()得到分段错误?

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

Scenario 1: Code: 场景1:代码:

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: 场景2:代码:

 ...
    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()? isdigit()有什么问题? I do not understand! 我不明白!

Probably because the compiler optimizes the isdigit function call from the code. 可能是因为编译器优化了代码中的isdigit函数调用。 That is it doesn't run it. 那就是它没有运行它。

Also note that isdigit expects a character, not a number. 另请注意,isdigit需要一个字符,而不是数字。 http://www.cplusplus.com/reference/clibrary/cctype/isdigit/ http://www.cplusplus.com/reference/clibrary/cctype/isdigit/

This is because isdigit can be defined as macro like this 这是因为isdigit可以像这样定义为宏

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

You call isdigit with integer value, but map array size is 256 elements. 使用整数值调用isdigit,但map数组大小为256个元素。 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. 因为if或else都没有做某事,所以它被移除了并且isdigit最终没有被调用。 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. 当您删除printf语句并且编译器对其进行优化时,将不会发生调用,因此不会失败。

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. 请注意,标题实际上可以省略,因为默认情况下程序将与标准C库链接,因此它可以工作。 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. 首先, isdigit(3)检查字符是否是数字。

The segmentation fault probably (I'm positive) happens because you haven't included stdio.h . 可能(我很肯定)发生了分段错误,因为你没有包含stdio.h

Then you're calling printf which uses variable arguments without knowing its prototype (undefined behavior). 然后你调用printf ,它使用变量参数而不知道它的原型(未定义的行为)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM