On a recent test question I was asked to print the output of the following program. I got the answer correct however this program caused me significant mental anguish as I didn't know what the behavior would be when writing to memory that is out of bounds of an array.
Here is the program under question, the comments are my notes:
#include <stdio.h>
#define MAX 4
void RecordArgs(int x);
int main()
{
RecordArgs(1);
RecordArgs(7);
RecordArgs(-11);
return 0;
}
void RecordArgs(int x)
{
static int i = 0;
int call_count = 0;
int arg_history[MAX] = {0};
if (call_count == MAX)
{
# call_count is not static and is initialized to 0 on each call
# as a result, under no circumstance can call_count == MAX and
# this printf is never executed
printf("Too many calls to RecordArgs\n");
}
else
{
# index out of bounds on second/third call (i + call_count will be 4??)
arg_history[i + call_count] = x;
++call_count;
++i;
for (i = 0; i < MAX; ++i)
printf("%d ", arg_history[i]);
printf("\n");
}
}
And the expected output:
1 0 0 0
0 0 0 0
0 0 0 0
When RecordArgs is called the second and third times where does the 7 and -11 values get written? I tried compiling it under different settings to see if I could get it two write to something it shouldn't but everything I've tried has resulted in that exact output w/o any segfaults.