0

I'm trying to understand the proper way to free the memory that is pointed to. In this case a pointer points to a new instance of a structure. An example is shown below

The structure is like this:

    struct MyData
    {
        unsigned short int MYID;    
        unsigned short int MYCMD;    
    }; 

Definition is below.

    MyData* injdataRx;

    myDataPtr = new MyData;  // create new instance

...do some stuff with loading values into what the pointer points to, ie. the fields.

Now if when I'm done with that structure and I want to insure that what the pointer points to (the allocated area) is freed, I do this.

    delete (myDataPtr);

Does that free the memory created by the "new" as in it knows that since myDataPtr is a pointer to type MyData that it will free the sizeof MyData? Is that what happens?

Any help in clarifying this is appreciated.

2
  • "Does that free the memory created by the "new" as in it knows that since myDataPtr is a pointer to type MyData that it will free the sizeof MyData?" Yes, as well as calling the object's destructor. Commented Feb 16, 2012 at 1:19
  • That's it. The hard part is remembering to always delete it. Or use smart pointers. Commented Feb 16, 2012 at 1:22

2 Answers 2

1

Yes it does. Basically, when you call new, the number of bytes allocated is recorded somewhere (this is not specified by the standard and is implementation dependent). Anyway, when you call delete, this number of bytes is referenced and that is how the system knows how many bytes to free even though you didn't tell it. The book keeping is done behind the scenes.

Sign up to request clarification or add additional context in comments.

Comments

0

As ildjarn and Duck already said in the comments, the answer is YES.

MyData * p;
p = new MyData;
delete (p);     // <- Yes, this frees the memory used for MyData.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.