0

I'm attempting to do a "find the bug" assignment, and this small bit of C code (not runnable as is) is supposed to have a bug in it. Unforunately I can't find one. I put it into runnable code and it seems to run as expected...is this a trick question or am I missing something? Any help is greatly appreciated.

Code snippit:

void example(int a[10]){
        int i = 0;
        do {
           a[i] = i++;
        }while (i < 10);
    }

My runnable code:

#include <stdio.h>
#include <string.h>

example(int a[10]){
    int i = 0;
    do {
       a[i] = i++;
       printf("%i", a[i-1]);  //decremented by 1 to offset i
    }while (i < 10);
}

int main(void)
{
   int arr[10];    
   example(arr);
   return 0;
}

Output:

0123456789
user1615559
  • 333
  • 2
  • 8
  • 18

1 Answers1

3

This is wrong and invokes undefined behavior:

a[i] = i++;

There is no sequence point specified for the assignment, increment or index operators, you don't know when the effect of the increment on i occurs.

Take a look to Question 3.1 of C-FAQ

David Ranieri
  • 39,972
  • 7
  • 52
  • 94