简体   繁体   English

简单的 for 循环突然使 C 中的程序崩溃

[英]Simple for loop suddenly crashes program in C

I am using MSVC via我正在使用 MSVC

cl file.c

with this very simple code:使用这个非常简单的代码:

#include <stdio.h>
#include <stdlib.h>
    
int
main(void) {
    
    int num = 50, pointNum = 60, max = 0;
    
    puts("Hello");

    for (int i = 0; i <= num; i++) {
        printf("%d\n", pointNum % i);
    }

    return 0;
}

but when I run it from the commandline, it just pauses and then crashes, only printing "Hello".但是当我从命令行运行它时,它只是暂停然后崩溃,只打印“Hello”。 I have no clue what is wrong, because it seems error free.我不知道出了什么问题,因为它似乎没有错误。

When i == 0 , you perform the math 60 % 0 which triggers division by zero.i == 0时,您执行数学60 % 0触发除以零。 That triggers undefined behavior which often will crash your program.这会触发未定义的行为,这通常会使您的程序崩溃。

In the very first iteration of the loop, the divisor is 0. But division by 0 is not possible.在循环的第一次迭代中,除数为 0。但除以 0 是不可能的。 Thus, it simply crashes.因此,它只是崩溃了。 Instead of this code snippet, I think you should use而不是这个代码片段,我认为你应该使用

for (int i = 1; i <= num; i++) {
    printf("%d\n", pointNum % i);
}

This will not provide any error.这不会提供任何错误。

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

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