Let me try and explain a little further.
String data needs [relatively] a lot of space. Each character in the string needs a
char
. Additionally, for C-style strings (char arrays), you need to end the string data with a literal 0.. known as the "null terminator" to mark the end of the string.
So the string "hello" needs at least 6 chars to hold it. One for each letter in the string, and another for the 0 null terminator.
So if you need 6 chars to hold that string... how can you hold it in a single
char*
pointer? The answer is: "you can't". The pointer is not where the string data is stored. The string data is stored elsewhere in memory... and your pointer simply points to the first char of that memory.
Example:
|
char buffer[6] = "hello"; // <- perfectly legal
|
Here we have an array of 6 chars. The array holds our 5 characters of string data + the null terminator.
Now to make that a pointer:
|
char* ptr = &buffer[0]; // <- ptr now points to the first char in our 'buffer' array
|
Again note that 'ptr'
does not contain the string data. 'buffer' does. This means that if we change buffer... the data 'ptr' points to will change. Example:
1 2 3 4 5
|
cout << ptr; // prints "hello" as you'd expect
buffer[0] = 'f'; // change the first character in our buffer
cout << ptr; // prints "fello" ... even though we didn't modify ptr!
|
That is the essence of pointers: they refer to data that exists elsewhere.
Expanding on this... if 'buffer' ceases to exist (as in... it's destroyed, or it goes out of scope)... then our 'ptr' is left "dangling"... ie, it's pointing to data which no longer exists. Dangling pointers are bad and are unsafe to read from/write to. In order to access a pointer, you must make sure it always points to valid data.
So now with that explained... let's understand what memcpy does.
Memcpy takes 2 pointers: a dest pointer, and a source pointer. It will read data from the source pointer and copy it to the dest pointer. It is assumed that both the source and dest pointers are valid and point to real memory that can be safely read/written.
Memcpy does not modify the pointer itself... but rather it modifies the data the pointer points to.
So now let's look at your code:
const char *binaryExt = std::string(".bin").c_str();
Your 'binaryExt' pointer is pointing to string data... but where is this string data? Does it actually exist?
What's happening is you're creating a temp object, pointing to its data, then the temp object immediately dies and your pointer is left dangling. It's similar to this:
1 2 3 4 5 6
|
const char* binaryExt;
{
std::string temporary = ".bin";
binaryExt = temporary.c_str(); // <- points to 'temporary's internal string data.
} // <- 'temporary' is destroyed here... it (along with its string data) no longer exists
// <- so here... 'binaryExt' is left as a dangling pointer. It points to garbage.
|