string childDisplayName = "";
creates an empty empty string (zero size and unspecified capacity). Using that as a data-buffer to write into is not likely to go well.
You can do this: string childDisplayName(MAX_PATH + 1, ' ');
to create a string with the proper space allocated.
Secondly, as @churill wrote, the address of a string is not the address of the characters in it. Instead use childDisplayName.data()
to get a char*
to the internal storage of the string that you can write in - but make sure not to write outside the range [data(); data() + size())
.
EDIT: A bit on how std::string
and .data()
works.
I made a small example program:
#include<iostream>
#include<string>
void print(const std::string& s)
{
std::cout << "String size: " << s.size() << '\n';
std::cout << "String contents: >>" << s << "<<\n";
std::cout << "String as c-string: >>" << s.c_str() << "<<\n";
std::cout << '\n';
}
int main() {
std::string bla = "";
auto bladata = bla.data();
for (int i = 0;i < 5;++i) {
bladata[i] = '!';
}
print(bla);
std::string bla2(10, '\0');
auto bla2data = bla2.data();
for (int i = 0;i < 5;++i) {
bla2data[i] = '!';
}
print(bla2);
}
When run this outputs:
String size: 0
String contents: >><<
String as c-string: >>!!!!!╠╠╠╠╠╠╠╠╠╠╠<<
String size: 10
String contents: >>!!!!! <<
String as c-string: >>!!!!!<<
What is going on here? First thing to notice is that an empty std::string
is created with zero size and unspecified capacity - looking in my debugger, I know that on my system that unspecified capacity is 15, so as long as I don't go beyond that nothing should crash. But this is obviously not something you should do in real code (writing here is strictly undefined behavior).
This means that the bla
string is size 0, and contains a 15 character char buffer, where I set the first 5 characters to '!'. So when I try to print its size()
or print it as a std::string
it is identical to any regular empty string. However, if I use .c_str()
to print the internal buffer directly, then it prints as any old char*
and just prints whatever is in memory until it encounters a null-character.
On the other hand, bla2
is initialized to contain 10 null-characters. That means that its size is 10, and its capacity is at least 10 (in my case it happens to also be 15). This means that after the loop it still reports as size 10, regardless of how many '!'s I put into the buffer, and when I print it as a std::string
it prints all the 10 characters it contains; both the 5 '!'s and the 5 '\0's. However, when I print it as a char*
it prints the 5 '!'s and then stop as soon as it encounters a null-character.