This is a fairly basic question and I am pretty sure I know the answer, but seeing as the consequence for being wrong is a segfault I figure I should ask. I have been using strlen() and the new char[] operator in the following way for quite some time now and just noticed something that threw up a red flag:
void genericCopy(char *somestring, char *someOtherString) {
someOtherString = new char[strlen(somestring)];
strcpy(someOtherString,somestring);
}
My question is, seeing as a string should be null terminated, should I be doing this as such:
void genericCopy(char *somestring, char *someOtherString) {
someOtherString = new char[strlen(somestring)+1];
strcpy(someOtherString,somestring);
someOtherString[strlen(someOtherString)] = '\0';
}
So far I have never had a problem with the first method, but that doesn’t mean I’m doing it right. Since the length being return by strlen()is the number of characters in the string without the null terminator so new isn’t reserving space for ‘/0’… At least I don’t think it is.
First of all, you should know that this function of yours is pointless to write, just use
strdup(if available on your system).But yes, you need an additional byte to store the
\0, so always do something likenew char[strlen(somestring)+1];. However, there is no need to manually add the\0;strcpyalready does this.You should use something like Valgrind to discover this and similar bugs in your code.
There is however an additional problem in your code; your code will always leak
someOtherString; it will not be returned to where you called it from. You either need to change your method to something like:and then get the copy as follows:
Or you need to change your method to something like:
and call it as:
If you’ll be using C++ you could also just change the method prototype to:
and call it as:
Then
someOtherStringwill be passed as a reference, and the new value you allocate to it will propagate outside of your method.