-3

I am a Computer science student and I feel like I am missing something very simple. Could you please help me out ?

#include <stdio.h>

void do_stuff(int *c) {

    static int a = 0;

    int b = 0;
    a+=3;
    printf("%d %d\n", *(c+a), c[b]);
    printf("%d %d\n", *(c+6), c[b]);
    printf("%d %d\n", c[6], c[b]);

}

int main (void){

    static int array[6] = {5,17,23,42,127,3};
    do_stuff(array);
    do_stuff(array);
    do_stuff(array);
    return 0;
}

This is the outcome of this code:

42 5

3 5

3 5

6 5

6 5

6 5

0 5

9 5

9 5

I don't get, why it is 6 5 for the second do_stuff(array). I thought it would be 0 5 for every print of second and third do_stuff(array). Then I thought maybe It was something to do with static a and I tried it without a variable, so just with the number 6. But the answer was the same. Could you please explain the reason for the outputs with the bold font? Thank you for your help.

Ian Abbott
  • 15,083
  • 19
  • 33
student
  • 15
  • 3
  • 1
    why did you think c[6] would be 0? – user253751 Jun 29 '22 at 15:20
  • What you're missing is that C doesn't do bounds checking on array accesses. It's your responsibility to make sure that the code never accesses memory outside the bounds of the array. – user3386109 Jun 29 '22 at 15:20
  • The first call to `do_stuff(array)` is also accessing out-of-bounds array contents, not just the second and third calls. – Ian Abbott Jun 29 '22 at 15:21
  • Just like @IanAbbott said the first call will have a global-buffer-overflow because you try to access the index 6 of array c. – Vladouch Jun 29 '22 at 15:23
  • Does this answer your question? https://stackoverflow.com/questions/26426910/is-accessing-a-global-array-outside-its-bound-undefined-behavior – n. m. could be an AI Jun 29 '22 at 15:33

1 Answers1

0

In an array with 6 elements, using index 6 will read the first position after the array, which is not 0. The read value depends on the underlying architecture and compiler implementation; depending if such memory position is mapped to your process or not, the OS may kill your application.

In your case, it looks like in memory you have the value of variable a stored just after the input array of do_stuff(), that's why printing c[6] basically prints the value of a.

Of course this is best described as undefined behavior and the source code is basically incorrect.

Jack
  • 1,488
  • 11
  • 21