I was asked this question in the MS written walkin-interview:
Find errors in the program below which is supposed to return a new string with \n
appended to it.
char* AddnewlinetoString(char *s)
{
char buffer[1024];
strcpy(buffer,s);
buffer[strlen(s)-1] = '\n';
return buffer;
}
I'd tried to code on myself and was able to get it working by making buffer variable global and having buffer[strlen(s)] = '\n'
. But did not know there were many other bugs in it.
I can see a few:
Length of input string not checked.
What if the strlen(s) > 1023
? You can fit a string of length at most 1023
in buffer.
Overwriting the last char with
\n
You are overwriting last char with newline. Your \n
should go where \0
used to be and you need to add a new \0
after \n
Variable buffer is local to function and you are returning its address.
Memory for buffer is allocated on stack and once the function returns, that memory is freed.
I would do:
char* AddnewlinetoString(char *s) {
size_t buffLen = strlen(s) + 2; // +1 for '\n' +1 for '\0'
char *buffer = malloc(buffLen);
if(!buffer) {
fprintf(stderr,"Error allocting\n");
exit(1);
}
strcpy(buffer,s);
buffer[buffLen-2] = '\n';
buffer[buffLen-1] = 0;
return buffer;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With