0

I am trying to print the value of globally declared array variable with the index out of boundary and getting 0 always.

I know already that C will not check the boundary values. But not sure whether this variable will be part of initialised data segment or BSS.

const int arr[] = {1,2,3,4};
int main()
{   
    printf("%d", arr[3840570000]);
}

Getting 0 as output.

  • 7
    Out-of-bounds indexing leads to *undefined behavior*. There's really nothing else to be said. – Some programmer dude Sep 02 '19 at 12:04
  • 1
    What value are you expecting? The value in that memory bit is empty thus gives 0. – nlreturns Sep 02 '19 at 12:05
  • arr[3840570000]=*(arr+3840570000) – J CHEN Sep 02 '19 at 12:08
  • C language:User always do right . give alot elasticity – J CHEN Sep 02 '19 at 12:10
  • @nlreturns I am expecting a Segmentation fault as this is out of bound access. – renga_in_stack Sep 02 '19 at 12:11
  • When declared locally within main(), getting SEGFAULT but not for global case. – renga_in_stack Sep 02 '19 at 12:12
  • 1
    @renga_in_stack If you want to know why your specific compiler on your specific platform produced code that does not cause a segfault in this case, you will have more success here by posting the generated (dis-)assembly together with information about your platform and asking about that, if there is something specific unclear to you about it. From the point of the C language there are no guarantees on behavior at all in this case. You cannot rely on getting segmentation faults. – walnut Sep 02 '19 at 12:15
  • You initialize `arr` with values. How could it be part of the BSS segment, which does not contain initial values? – Eric Postpischil Sep 02 '19 at 12:18
  • @uneven_mark Actually i tried this in online editor. I will post the info you requested after running it in my Ubuntu PC – renga_in_stack Sep 02 '19 at 12:18
  • As you know, accessing an array out of bounds leads to undefined behavior. But "undefined behavior" does *not* mean, "segmentation fault"! (If the behavior was defined as giving you a segmentation fault, it wouldn't be undefined, would it?) Undefined behavior means *anything* can happen, and in general you can't predict what it might be. Asking why you didn't get the behavior you expected is like asking, "I crossed the street when the sign said DON'T WALK. I expected to get a warning from a policeman. Instead I got run over by a truck. Why?" – Steve Summit Sep 02 '19 at 12:30
  • Thanks Steve for giving much clarity on undefined behavior. – renga_in_stack Sep 02 '19 at 12:34

0 Answers0