I tried to access an array element greater than which was passed in the search function but it did not cause a segmentation fault. Here is the code in which I was trying to access the element:

bool search(int value, int values[], int n)
    for(int i = 0; i < n+2; i++)
        if(values[i] == value)
        return true;
    return false;

Accessing an array element that's beyond the boundaries of an array has an undefined behavior. This means that it could cause a segmentation fault, but it doesn't always have to.

  • Can you please elaborate a bit on why is this so, Thank you. Oct 13 '16 at 12:24
  • @RahulNagurtha why what exactly?
    – kzidane
    Oct 13 '16 at 12:35
  • I was asked in interview regarding the same. The question was "What is the probability that you get a segmentation fault if you access a byte which is just after the end of the character array ?" , So i just want to know why accessing beyond the boundary doesn't always result in segmentation fault and what is the probability of segmentation fault. Oct 13 '16 at 12:39
  • @RahulNagurtha, well, not sure there's a defined probability for this (or generally any) undefined behavior. AFAIK, a segfault generally happens when your program tries to access memory that it doesn't own.
    – kzidane
    Oct 13 '16 at 13:23
  • Does the probability of getting Seg fault depend on whether the array is allocated on stack or heap ? Oct 13 '16 at 15:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .