on new and structures and pointers

say I have a pointer to a structure, ptr and I dynamically allocate memory to it using the new operator. Within that structure is another pointer, memberPtr, to some other datatype which is also assigned a dynamically created value.

1) When I call delete on ptr, the delete operator only frees up the memory of the structure pointed to by ptr and leaves the memory pointed to by memberPtr alone, leading to a memory leak, am I right?

2) If yes, does (1) happen all the time or vary depending on compiler implementations?

3)
reason I ask this is because I have a function, functionA() that calls functionB() and I want to pass a dynamically allocated structure which has as its member, a pointer to a local variable of functionA to functionB and I want to ensure that when functionB calls delete on that structure, it does not call delete on the local variable of functionA as well, can this be done?
Last edited on
When you delete an allocated object, first it's destructor is called and then the memory is freed. If your destructor doesn't delete your member that will be a memory leak (unless there are other pointers to it).
If you have not written the class/structure yourself, there is nothing that you can do externally to influence how it goes about its business. (Unless you set the pointer to NULL manually before the destructor is called, but this is a hack solution and I think does not apply to your case.)

If you have written the structure and you have provided no destructor, or you have provided destructor that does not explicitly deallocate the memory pointed by the aforementioned pointer then it will not be done automatically.

On a side note: Destructors should generally not deallocate resources that are not allocated by the constructor of the class or inside the class's methods. There are exceptions. The auto_ptr template class does that, but it is somewhat quirky in that way.
Topic archived. No new replies allowed.