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.
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.