Pergunta de entrevista da empresa SpaceX

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; }

Respostas da entrevista

Sigiloso

21 de mai. de 2013

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.

2

Sigiloso

17 de mai. de 2013

Actually, it's not possible. Typically in code questions, if they don't specify constraints on a variable, assume the worst. In this example, if array_size was negative, then the for loop would never run (i.g. index = 0, array_size = -1, then index < array_size would be false on the first go). Same goes if array_size is zero. If array_size is positive, then it is constrained since array_size can never equal infinity.

2