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?
c++ - What is a dangling pointer? - Stack Overflow
Dangling pointers in C - Stack Overflow
Dangling Pointers
[C++] Wikipedia dangling pointer example
Videos
A dangling pointer is a pointer that points to invalid data or to data which is not valid anymore, for example:
CopyClass *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:
CopyObject *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.
Dangling pointers are only a concern if you try to use them after you've freed them.
Yes, it's possible that a new allocation can return the same address that x has. But you can never know whether this is going to happen, so you still can't use x any more. It would just be a coincidence if its address became valid again.
Even if you keep allocating and freeing the same size, there's no expectation that it will keep reusing the same address.
For safety you must assume that a freed pointer will never become valid again.
The term dangling pointer means that whatever address in memory it points to is invalid. If you make it valid, like your 2nd malloc, then the address becomes valid. If you store the same address in two different variables (via your assumption) both are valid pointers:
Copy#include <stdio.h>
#include <stdlib.h>
struct s { int i; };
int main() {
struct s *p = malloc(sizeof(struct s));
printf("before: %p\n", (void *) p);
free(p);
// p is dangling
printf("after: %p\n", p);
struct s *p2 = malloc(sizeof(struct s));
// p and p2 are valid
printf("before: %p\n", (void *) p2);
free(p2);
// p and p2 are dangling
printf("after: %p\n", p2);
}
and the output from my pleasingly corroborative malloc:
Copybefore: 0x561b73d3b260
after: 0x561b73d3b260
before: 0x561b73d3b260
after: 0x561b73d3b260