Is it possible for the following function to go into an infinite loop given an array and its size in C: void foo( int* array , int array_size ) { int index = 0; for( ; index < array_size ; index++) array[ index ] = 0; }
Sigiloso
Bonus points if you consider the case of a buffer overflow. If array_size is greater than the size of the buffer pointed to by array then the code may behave unpredictably. In particular, if array is stack-allocated then the loop may lead to stack corruption, and depending on the calling code this may cause the program to loop infinitely. int array[5]; int conditional = 0; while( !conditional) { conditional = 1; foo(&array, 6); } It is not clear to me whether the loop in the foo function could loop infinitely. If the index variable were somehow clobbered to 0 but the array_size variable remained greater than zero this could be possible. Since array_size is higher in the stack than index they would likely both be clobbered to zero, causing the loop to terminate. However, if foo was inlined and array_size a constant in the calling context it may get hardwired into the opcode and not stored on the stack. In this case index could get zeroed out while array_size remained > 0, causing the loop in foo to not terminate.