Interview Questions

find the bug in the following code which concatenates...

Microsoft Interview Questions and Answers


(Continued from previous question...)

59. find the bug in the following code which concatenates...

Question:
1) find the bug in the following code which concatenates 2 strings ---

char * concatenate(char *s1,char *s2)
{
char buffer[1024];
int i=0;
while(*s1)
{
buffer[i++]=*s1;
s1++;
}

while(*s2)
{
buffer[++i]=s2;
s2++;
}
return buffer;
}



maybe an answer1:

1) There is a gap in between two strings (have some garbage value).
2) string not ended with '\0'.
3) size of buffer not enough, if size of (S1+S2) > 1024.
4) In copying second string [ buffer[++i]=s2; ] RHS should be *s2.



maybe an answer2:

> return pointer to stack memory
2) size not checked
3) we were doing i++ then we switched to ++i so there is has been a double increment
4) and no null assigned at end



maybe an answer3:
Total Six bug in the codebr> br> 1. No validation of the inputs, if NULL is passed to any of the input function will crash while dereferencing (while(*s1))
2. Buffer is not allocated based on the sum of the length of the input string, which will lead to buffer overrun (in this case stack overrun) if the combined string length is greater than 1024 (char buffer[1024])
3. Address of the local variable is returned, buffer should be allocated on heap (dynamic memory) and its pointer should be returned (return buffer)
4. ++i is creating a byte between the two string used for concatenation to contain garbage value (buffer[++i]=s2).br> 5. pointer is being assigned to char value (buffer[++i]=s2)
6. The combined string is not null terminated

(Continued on next question...)

Other Interview Questions