mufasa said:
Am I not trying to break any ownership rules herein (see below) :
There is no real ownership semantic here. You're allocating memory yourself,
and you're deallocating it yourself.
#include <string>
#include<iostream.h>
using namespace std;
int main()
{
char * a = new char('a');
cout << *a <<endl; //prints 'a'
char * c = new char();
c = a;
Like in the previous example, you loose the allocated memory here. Note that
c is only a pointer, just as a. "c = a" means that you let c point to the
very same memory location that a was (and still is) pointing to (the one
you allocated previously with "new char('a')"). You didn't do anything to
the memory that you allocated with "new char()", you only let the pointer c
point somewhere else. That memory is still there, but you don't have any
pointer pointing to it. So that memory is lost, unaccessable, undeletable.
This frees the memory allocated with "new char('a')" that both a and c are
pointing to.
cout << *a <<endl; //prints '0'. which means that 'delete c'
//did delete the contents
This invokes undefined behavior (anything can happen, from printing '0' to a
system crash). You're not allowed to dereference a pointer that points to
memory that was already freed.
owned by a! right?
delete a;
delete a; //why does this double delete
work!
}
Again, undefined behavior. It might "work" (i.e. not crash), but it could
also crash or do anything else. The C++ standard doesn't give you any
guarantee about what happens. It might be system or compiler specific or
even depend on the moon phase.