Here:
const char* ptr = new char[strlen("is visible") + 1];
ptr = "is visible";
The second line assigns a pointer to the string literal "is visible"
to ptr
. The pointer to the dynamically allocated char
array you allocated in the first line is lost. Its a memory leak. Because of this bug, the two versions really do the same apart from the memory leak. They return a pointer to a string literal.
Note that string literals have static storage duration (cf Is a string literal in С++ created in static memory?), hence the usual issues of returning a pointer to a function local object does not apply. However, both of your function are rather useless. They do not, as their name suggests, allocate memory that you can then use to store other stuff.
// here later memory deallocation required i.e Okay
Yes it would be required to deallocate the memory allocated via new
. Though, it is not Okay
, because you do not have the pointer to that memory anymore.
ptr = "is visible";
This copies a pointer. If you want to copy the string literal into the allocated char
array you must copy the char
s (eg strcpy
). Arrays cannot be assigned like that. Actually ptr
is not an array. ptr
is just a pointer. Don't confuse arrays with pointers. new char[strlen("is visible") + 1]
allocates an array and returns a pointer to its first element.