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.
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
No, a '\n' is a new-line in c, just like in Java (Java grabbed that from C). You've identified one problem: if the input string is longer than your buffer
, you'll write past the end of buffer
. Worse, your return buffer;
returns the address of memory that's local to the function and will cease to exist when the function exits.
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