Why am I not getting a segfault error with this simple code?

I should show an error when I access an element outside the array (without creating my own function for it). So I just thought it was necessary to access the value from the array in order to call segfault, but this code doesn't crash at all:

int main(){
    int tab[4];
    printf("%d", tab[7]);
}

Why can't I get an error message when I do this?

+4
source share
3 answers

When you invoke undefined behavior , anything can happen. The program may crash, it may display strange results, or it may appear that it is working correctly.

, , , , printf, undefined.

, 63. 7 7000, segfault.

, , , , .

+8

, , , "undefined" . , C. . "".

int tab[4]; , 4 . tab - . , , , .

printf("%d", tab[7]); , 8- tab. ...

  • tab 1000 (), 1000.
  • tab int, sizeof(int), , 4 8 . 8.
  • tab[7] (7 * 8) + 1000 = 1056 8 . 1056 - 1063.

. . , , , C.

, tab[7] 1056 1063.

, .

int main(){
  int tab[4];
  printf("sizeof(int): %zu\n", sizeof(int));
  printf("tab: %d\n", tab);
  printf("&tab[7]: %d\n", &tab[7]);

  /* Note: tab must be cast to an integer else C will do pointer
     math on it. `7 + tab` gives the same result. */
  printf("(7 * sizeof(int)) + (int)tab: %d\n", (7 * sizeof(int)) + (int)tab);
  printf("7 + tab: %d\n", 7 + tab);
}

, , &tab[7] - , tab, , .

$ ./test
sizeof(int): 4
tab: 1595446448
&tab[7]: 1595446476
(7 * sizeof(int)) + (int)tab: 1595446476
7 + tab: 1595446476

1595446476 - 1595446448 - 28. 7 * 4 - 28.

+2

An array in C is just a pointer to a block of memory with a starting point at, in this case, an arbitrary location tab[0]. Of course, you set a limit 4, but if you pass by this, you will get access to random values ​​that are located behind this block of memory. (that is, the reason he probably prints weird numbers).

+1
source

Source: https://habr.com/ru/post/1667395/


All Articles