这会导致段错误消息吗?

标签 c segmentation-fault initialization

如果我有以下代码,是否会导致段错误?

 #include <stdio.h>
 #include <stdlib.h> 

int main() {
    int i;
    int n = 30;

    while(i < n) {
            printf("%d ", i);
            if(i % 3 == 0) {  
            n--;
            } else {
            n = n -2;
            }
   i = i + 2;

    }
return 0;
}

当我运行它时,我没有得到任何段错误,但也没有得到任何输出。我们是否总是假设整数 i 可以是内存中的任何数字?我知道它不会被初始化为 0,对吗?

最佳答案

对于局部变量是(在堆栈中分配,值未定义) 查看答案:What happens to a declared, uninitialized variable in C? Does it have a value?

如果“int i”在 main 之外声明(作为全局或静态变量,它将为零,并且您的输出将如下所示 “0 2 4 6 8 10 12 14 16”

因此,尽管编译器可以选择崩溃,但这段代码不太可能导致段错误。但您并没有真正访问越界内存,而只是访问堆栈上的某些值。在这种情况下,我是一个指针,并且您尝试取消引用它,那么它很可能会导致段错误。

关于这会导致段错误消息吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28554467/

相关文章:

java.lang.OutOfMemoryError : Java heap space while initialising an array 错误

c++ - `-g -rdynamic` gcc 标志是否显着减慢应用程序执行(增加性能消耗)?

c - about/proc读写函数

c - rand() 一直给我相同的数字并通过变量减少 4

c - 增加 C 中的指针导致段错误,即使它在数组大小内

c - 在以下 c 代码中出错 [段错误]

javascript - Node js 脚本崩溃 : Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

c - pthread和printf的C性能差

c++ - 使用连续无符号整数列表初始化 std::vector<unsigned int>

python - 初始化一个列表并找到该列表的平均值