I got a problem today. It had a method and I need to find the problem in that function. The objective of the function is to append new line to the string that is passed. Following is the code
char* appendNewLine(char* str){
int len = strlen(str);
char buffer[1024];
strcpy(buffer, str);
buffer[len] = '\n';
return buffer;
}
I had identified the problem with this method. Its kind of straight forward. The method is having a potential of having array’s index out of range. That is not my doubt. In java, I use ‘\n’ for newline. (I am basically a Java programmer, its been many years I’ve worked in C). But I vaguely remember ‘\n’ is to denote termination for a string in C. Is that also a problem with this program?
Please advise.
Theres quite a few problems in this code.
Possible solutions to that can either be allocating the memory on the heap (with a combination of strlen and malloc), or using strncpy and accepting the cut off of the string.
Solution: Append ‘\n’ and ‘\0’ to null terminate the new string.
To expand your understanding of these problems, please look up what C-style strings are, potentially from here. Also, teach yourself the difference between variables allocated on the stack and variables allocated on the heap.
EDITed: AndreyT is correct, the definition of length is valid