c++ memory leak with structures?
Let's say I allocate memory to a pointer to a structure:
CatStructure * cat; // assume a CatStructure has name and weight
Let's say I initialize cat to:
cat->name = "pippy";
开发者_运维技巧cat->weight = 100;
If I save a reference to cat->name and cat->weight, do I still need to save a reference to cat? In other words, is it necessary to save a reference to a pointer to a structure if I've already saved references to its members?
CatStructure *cat;
does not allocate memory for the given struct, it just gives you a place to store a reference to a pointer. We'll say that you know this, and that you're new
ing correctly to actually allocate memory.
Every new
must be matched with a corresponding call to delete
or you will leak memory. Technically if you're saving a reference to one of the members correctly you could do some pointer math to recover the reference to the struct, but that's unnecessarily obtuse. Just save the pointer so you can clean it up later.
if you delete the structure, any references to its pointers or members will no longer be valid. those invalid pointers/references are called 'dangling'.
精彩评论