I wrote this code today, just out of experimentation, and I’m trying to figure out the output.
/*
* This code in C attempts to exploit insufficient bounds checking
* to legitimate advantage.
*
* A dynamic structure with the accessibility of an array.
* Handy for small-time code, but largely unreliable.
*/
int array[1] = {0};
int index = 0;
put(), get();
main ( )
{
put(1); put(10), put(100);
printf("%6d %5d %5d\n", get(0), get(1), get(2));
}
put ( x )
int x;
{
array[index++] = x;
}
get ( index )
int index;
{
return array[index];
}
The output:
1 3 100
There is a problem there, in that you declare ‘array’ as an array of length 1 but you write 3 values to it. It should be at least ‘array[3]’. Without that, you are writing to unallocated memory, so anything could happen.
The reason it outputs ‘3’ there without the fix is that it is outputting the value of the global ‘index’ variable, which is the next int in memory (in your case – as I said anything could happen). Even though you do overwrite this with your
put(10)call, the index value is used in as the index in the assignment and then post-incremented, which will set it back to 2 – it then gets set to 3 at the end of theput(100)call and subsequently output via printf.