Undo interview question

Discuss this code snippet; can you spot any bugs and if so, how to fix them (note, the code in the interrupt handler cannot be modified): // The following is known: // 1. You can be interrupted at any time. // 2. The interrupt will be repeatedly raised every 'x' micro seconds. // Please answer: // 1, Where is the bug in this code? // 2. How you would fix it? #include<stdio.h> #include<signal.h> #include<unistd.h> #include<assert.h> typedef struct { int a; int b; int c; int done; } foo; foo bar; void sig_handler(int signo) { if ( !bar.done ) { bar.c = bar.a + bar.b; bar.done = 1; } } int main(void) { bar.done = 0; bar.a = 0; bar.b = 0; signal(SIGINT, sig_handler); while(1) { for (int i=1; i < 20; i++) { for (int j=1; j < 20; j++) { bar.a = i; bar.b = j; while( !bar.done ); assert( bar.c == bar.a + bar.b ); bar.done = 0; printf("Loop done %d\n", bar.c); } } } }

Interview Answer

Anonymous

26 Sept 2017

I found the bug and discussed the fix.