Segfault doesn't happen [duplicate]

别来无恙 提交于 2020-01-07 09:01:25

问题


I have the following c code:

#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));
}

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: compiled with gcc version 4.9.2 (Debian 4.9.2-10)


回答1:


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.

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.

Some examples :

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 variables are initialized automatically

{
    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 
}



回答2:


Dereferencing an uninitialized pointer invokes undefined behavior. This means anything can happen. The program could crash, it could generate strange results, or it could appear to work properly. It all depends on whatever random value happens to be in that pointer.

There's no guarantee that invoking undefined behavior will cause a crash.



来源:https://stackoverflow.com/questions/41243889/segfault-doesnt-happen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!