Microsoft Interview Question
Software Engineer / DevelopersThis is the case of exceeding the bounds of an array..
The program will crash at some point ...
because the null value in the input array has been overwritten by 'h' hence source will never find null and will never terminate.
Since the source and destination pointers point to locations within the same array... the loop starts off with writing input[0] to input[1] and subsequently the dest and source pointers are kept at a distance of +1 apart from each other, the first character of the input character is written all over the array...now when the dest pointer is at null char of input[] the source pointer is at the character just before null char.. at this point the null char gets overwritten therefore the loop condition cannot terminate.. this program will probably crash as a result of segmentation fault or loop for an indefinite time.
Does the expression
while(*source != NULL)
involve a typo or is it a trick? Because it should be
while(source != NULL)
since there is no point in comparing if the "value pointed by a pointer" is NULL.
Initial state
H E L L O X X X X X X X X X X X X X X X X X X X X X X X X X
|-----Array--------|------- Memory continues ----------
Intermediate state
H H H H H H H H H H H H H H H H H H H H H H H H ----------
Stack Overflow exception
or error in Memory access out of range
What exactly the exception would came out of this function execution ?
dest pointer should be allocated memory before it is some character are added.
dest = new char[strlen(source)];
Actualy this program does not output anything. But if "what will happen" is asked, until the while block finds a null character the loop continues and dest will be set to null. Because Dest point to the +1 memory block of source this code will do lots of wrong memory changes.
- cac September 18, 2010