Microsoft Interview Question
Software Engineer in Tests2 mistakes.
1) There is a gap in between two strings (have some garbage value).
2) string not ended with '\0'.
/* find the bug in the following code which concatenates 2 strings ---*/
char * concatenate(char *s1,char *s2)
{
/* 1) s1 and s2 can be null and the method never checks if they are initialized */
char buffer[1024]; /* 2) can produce overflow because lenghts of s1 and s2 are unknown */
int i=0;
while(*s1)
{
buffer[i++]=*s1;
s1++;
}
while(*s2)
{
buffer[++i]=s2; /* 3) ++i jumps an additional character */ /* 4) can't pass char* to char */
s2++;
}
return buffer; /* 5) buffer doesn't end with null character */
/* 6) can't return a pointer to a previous declared function, must use malloc, not static */
}
dont u all think that the two strings are having ther original pointers ass1 and s2... now if we perform s1++,we are changing s2,which means that access to array is lost from begining,hence..it will give compiler error..i.e."lvalue required in function main"
Total Six bug in the code
- Swamy September 13, 20111. 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).
5. pointer is being assigned to char value (buffer[++i]=s2).
6. The combined string is not null terminated.