Microsoft Interview Question
Software Engineer / DevelopersHi Sambit,
In the above code you've given there is NO error. Are you sure you are not missing something? Can you elaborate on the "copy algo".
P.S. Only the first element - buf[0] - will be initialized to 0. It will be displayed a null character if you print it as %c or 0 if you print it as %d.
Let us know.
Cheers
SORRY There IS a bug in this. I overlooked it at first.
Actually it is a warning thrown by the compiler- you are trying to return an address of an automatic variable local to copy function.
Initially I thought I'll make it static or global.. but guess what it will even then compile and give the correct output. Try this:
#include<iostream>
using namespace std;
char * copy (char *);
int main()
{
char *result;
char something='x';
char *whatever = &something;
result = copy(whatever);
result[0] = 'X';
cout<<result;
return 0;
}
char * copy(char *p)
{
//I skipped char buf[1000]={0} coz its the null character
char buf[1000] = {'A','B','C'};
//copy algo[I skipped code here]
return buf;
}
There are 2 bugs in this code.
First, is that if the length of source string is greater than 1000, we will have buffer overflow here and crush.
Second - returning the adress of local variable. the return value shall be allocated using new operator.
can u pls explain wat will be the consequences of this bug.. as in.. can u explain "the return value shall be allocated using new operator" ??
Buffer overflow will cause stack demage and crush.
Returning adress of local variable can cause unexpected behaviour, because after function return the memory can be oerwritten by some ohter routine. So the correct function shall look like this
char * copy(char *p)
{
char* buf = new char[strlen(p)];
//copy algo[I skipped code here]
return buf;
}
MS IDC makes fool of people.
People have to come to office on weekends due to workload and do night outs, no work life balance. They pay 10-20% more make people labour.
Do take the feedback from employees before joining MS.
And work is junk, all junk wor from Redmond is transferred to IDC. Ask any team, whether they design, implement products or just do porting or maintenance or make tools.
string greater than 1000 will not cause buffer overflow always.
- Anonymous May 28, 2010returning local variable is the bug