Segfault不会发生 [英] Segfault doesn't happen

查看:104
本文介绍了Segfault不会发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下C代码:

#include <stdint.h>
#include <stdio.h>

int main (){
    uint8_t *array;
    int i=0;
    for(;i<32120;i++)
        printf("Array[%d] = %d \n",i,*(array+i));
}

因为我没有为数组声明内存,所以我希望这段代码在第二次迭代时出现段错误,但事实并非如此(它发生在我的树莓派上,i == 3295,并且我的随机值较大) debian虚拟机.

As I don't declare the memory for array, I would expect this code to segfault on the second iteration, but it's not the case (it happens at i==3295 on my raspberry, and larger random i value on my debian virtual machine.

我在这里想念什么吗?

Am I missing something here ?

ps:使用gcc版本4.9.2(Debian 4.9.2-10)编译

ps: compiled with gcc version 4.9.2 (Debian 4.9.2-10)

推荐答案

当您尝试访问非分页的内存块时,会发生分段错误.访问未初始化的指针是一种未定义的行为,使用未初始化的下标访问内存也是未定义的^ 2.

The Segmentation faults happens when you're trying to access non-paged memory block. Its an undefined behavior to access non initialized pointer, also accessing to memory with uninitialized subscript is undefined^2.

未定义的行为可能会导致分段错误,可能导致数据丢失,可能导致papa noel从您的终端发出!!或....但是在大多数情况下,与内存相关的未定义行为问题会导致分段错误或类似问题,但是为什么在引用引用的索引之前就不会出现分段错误?

Undefined behavior may result in segmentation faults, may result data loss, may result papa noel comes out from your terminal !! or .... But in most cases, memory related undefined behavior issues result in segmentation faults or similar issues, but why you're not getting segmentation fault until dereferencing index you mentioned?

这是因为您没有初始化指针数组,所以存储在该数组所占用的内存中的值不会更改.完全根据您的机会,此变量将保存一个地址,该地址被分页到您的应用程序虚拟内存空间上.如果将其初始化为零,或者使其为静态,或者将其定义为全局变量,则在其第一次取消引用时肯定会遇到分段错误.

This is because you doesn't have initialized pointer array, the value stored in the memory which array occupied doesn't changed. Its totally by your chance that this variable holds an address which is paged on you applications virtual memory space. If you initialize it by zero or make it static or defining it as global variable you will definitely get an segmentation fault on its first dereference.

一些例子:

手动初始化为NULL(零)

Manual initialization to NULL (zero)

{
   int * ptr = NULL;
   int index;
   *ptr = 1;    // segfault
   *ptr[index] = 1; // may not segfault, based on uninitialized value stored in index
}

静态变量会自动初始化

{
    static int * ptr; // static variable (default initialized to 0)
    *ptr = 1;   // segfault
}

全局变量也会自动初始化

Global variables are initialized automatically, also

int * ptr; // global variable (default initialized to 0)
{
    *ptr = 1;  // segfault
}

堆栈中的本地存储变量未初始化,并保持内存占用值不变

Local storage variables in stack are uninitialized and keep the value on memory occupied untouched

{
    int * ptr; // unintialized
    *ptr = 1;  // may segfault or may not 
}

这篇关于Segfault不会发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆