I don't understand concept of dangling pointer, was googling around, and writing test methods to find one.
I just wonder is this a dangling pointer? As whatever example I found was returning something, here I'm trying something similar!
void foo(const std::string name)
{
// will it be Dangling pointer?!, with comments/Answer
// it could be if in new_foo, I store name into Global.
// Why?! And what is safe then?
new_foo(name.c_str());
}
void new_foo(const char* name)
{
// print name or do something with name...
}
A dangling pointer is a pointer that points to invalid data or to data which is not valid anymore, for example:
This can occur even in stack allocated objects:
The pointer returned by
c_str
may become invalid if the string is modified afterwards or destroyed. In your example you don't seem to modify it, but since it's not clear what you are going to do withconst char *name
it's impossible to know it your code is inherently safe or not.For example, if you store the pointer somewhere and then the corresponding string is destroyed, the pointer becomes invalid. If you use
const char *name
just in the scope ofnew_foo
(for example, for printing purposes) then the pointer will remain valid.