So in attempting to learn how to use C-Strings in C++, I'm running into issues with memory allocation.
The idea here is that a new string is created of the format (s1 + sep + s2) The text I'm using provided the header, so I can't change that, but I'm running into issues trying to set the size of char str[]. I am getting an error saying that sLength is not constant, and therefore cannot be used to set the size of an array. I'm relatively new to C++ so this is a two part question.
Is this strategy actually allocating memory for the new array?
How do I set the array size correctly if I can't get a constant value using strlen(char*)?
char* concatStrings(char* s1, char* s2, char sep){ int sLength = strlen(s1) + strlen(s2) + 3; //+1 for char sep +2 for \0 at end of string char *str = new char[sLength]; strcpy (str, s1); str [sLength(s1)] = sep; strcat (str, s2); return str; }
Edits made, so now I'm getting no compiler errors but...
The call to the function is here:
char* str = concatStrings("Here is String one", "Here is String two" , c);
cout<< str;
My output becomes:
Here is String onec==================22221/21/21/21/2 /(etc.)/ Here is String two
sizeof(s1)
returns the size of a pointer variable, not the length of the array which it points to. Since you know thats1
points to a C-string, you should use thestrlen()
function instead.Error is returning address of local array variable
str
. Its scope is within functionconcatStrings()
where you declared, and can't be accessed once control returns from the function.To access it outside, you need to dynamically allocate memory for the string from the heap using the
new
operator.And after the program is done using the string returned from
concatStrings
it should ensure to free up the memory by invokingdelete
I've also edited the
concatStrings()
function to usestrlen
instead ofsizeof
UPDATE: Thanks for pointing out that we only need to do +2 and not +3 and for making sure a '\0' needs to be appended after
str1
andsep
before invokingstrcat
You can allocate the resulting string memory dynamically (at run-time, on the heap), using
new[]
in C++ (ormalloc
for a more C-like style):Note that this memory must be released somewhere in your code, using
delete[]
if it was allocated withnew[]
, orfree()
if it was allocated usingmalloc()
.This is quite complicated.
You will simplify your code a lot if you use a robust C++ string class like
std::string
, with its convenient constructors to allocate memory, destructor to automatically free it, andoperator+
andoperator+=
overloads to concatenate strings. See how your code is simplified usingstd::string
:(Note that using raw C strings can also make your code more vulnerable to safety problems, since you must pay lot of attention to proper sizing destination strings, avoid buffer overruns, etc. This is another reason to prefer a RAII robust string class like
std::string
.)