dangling pointer

Does delete n_ptr delete the memory n_ptr is pointing to?

1
2
3
4
5
A * n_ptr = new A();
	cout<<n_ptr->value;
	cout<<endl<<n_ptr<<endl;
	delete n_ptr; 
	cout<<n_ptr;
Does delete n_ptr delete the memory n_ptr is pointing to?

What does "delete the memory" mean?


It causes the destructor function of the object it points at to run, and tells the operating system that you no longer care what happens with the memory that object occupies. That's all it does.
Last edited on
Delete the memory
= meaning the block of allocated memory created for object A with new A() is released back to the os .

The coding is a little confusing it one would think its deleting the pointer(delete n_ptr).
BTW, how can I destroy object A created by new A()?

A * n_ptr = new A();

is this done by the delete command as well?
Last edited on
Then yes, the memory is available for the OS to reuse (or rather, your memory manager to reuse).

BTW, how can I destroy object A created by new A()?
A * n_ptr = new A();

Like this:
delete n_ptr;
Thx

Last Q

When we do this: delete n_ptr are we decoupling the pointer from the address it is pointing to? I also didn't know you could destroy an object by deleting its pointer.

Finally, if I want to use n_ptr again, I'm getting a redeclaration error even though deletion has occurred and object deleted. Any way to recycle?

Thats all






Last edited on

When we do this: delete n_ptr are we decoupling the pointer from the address it is pointing to?


Before you call delete, n_ptr points at some piece of memory. After you call delete, n_ptr is completely, 100% unchanged. It is identical to how it was before. It will be pointing at the exact same memory address it was before.

Finally, if I want to use n_ptr again, I'm getting a redeclaration error even though deletion has occurred and object deleted. Any way to recycle?

Don't redeclare it. Just use it.

1
2
3
int* n_ptr = new int;
delete n_ptr;
n_ptr = new int;
Topic archived. No new replies allowed.