Quote Originally Posted by papagym177 View Post
In jumping into C++ it says something like this: It's not necessary but when you delete a pointer it's a good idea to reset it as a null pointer. That if your code try's to dereference the pointer after being freed, your program will crash. This happens to a lot of experienced programmers This could corrupt users data.
delete p_int;
p_int = NULL;

This raises a lot of questions for me as a beginners.

1. If you can deference a pointer after the memory is freed, why can't you just delete the pointer?

2. If you can do 1, how do you delete the pointer using code?

3. Every thing I've read says that free memory is handed out in a sequenced order. I don't believe that is true at all. I may be wrong. Why can't you put the data in any number of places if it will fit. Isn't the compiler smart enough to know where bytes (bits)and pieces are stored?

4. If you storing anything in free memory must use a pointer to it?

5. Can a pointer or something similar be used with stack memory?
1) "Deleting" a pointer causes it's destructor to be called (if any) and then relinquishes ownership of that chunk of memory back to the system to be used elsewhere. So the pointer itself is still going to contain that memory address. If you then try to dereference the pointer things may seem to work normally for a while or the program may well crash at any point. Setting it to NULL ensures that an error will be raised the moment you try to dereference the invalid pointer.

2) Just as you have it: "delete p_int;". For an array you would use the "delete[] p_int;".

3) No, the implementation is free to dole it out however it likes.

4) It sounds like you're asking if an allocated chunk should have at least one pointer attached to it? If so, yes, because otherwise you'd have a memory leak.

5) Absolutely! Just don't "delete" something that hasn't been allocated with "new".

Oh, and once you understand how pointers work, be sure to study up on the principles of RAII...