Videos
pointer that does not point to a valid object
A dangling pointer is a pointer that points to invalid data or to data which is not valid anymore, for example:
Class *object = new Class();
Class *object2 = object;
delete object;
object = nullptr;
// now object2 points to something which is not valid anymore
This can occur even in stack allocated objects:
Object *method() {
Object object;
return &object;
}
Object *object2 = method();
// object2 points to an object which has been removed from stack after exiting the function
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 with const 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 of new_foo (for example, for printing purposes) then the pointer will remain valid.
A dangling pointer is a (non-NULL) pointer which points to unallocated (already freed) memory area.
The above example should be correct given that the string is not modified through new_foo.
The lecture notes of my professor mention that when u deference a dangling pointer, you would get an error, but I am not getting error, rather different answers on different compilers, what's happening here?
I think memory safety is an architectural property, and not of the language.
I'm trying to decide what architectural decisions to take so future team members don't mistakenly create dangling pointers.
Specifically I want to prevent the cases when someone stores a pointer in some struct, and forgets about it, so if the underlying memory is freed or worse, reallocated, we'll have a serious problem.
I have found 3 options to prevent this ...
Thug it out: Be careful while coding, and teach your team to be careful. This is hard.
Never store a pointer: Create local pointers inside functions for easy use, but never store them inside some struct. Use integer indices if necessary. This seems easy to do, and most safe. Example: Use local variable
int *x = object->internal_object->data[99];inside a function, but never store it in any struct.Use a stack based allocator to delete and recreate the whole state every frame: This is difficult, but game engines use this technique heavily. I don't wish to use it, but its most elegant.
Thanks