I'm trying to free some memory taken by structures.
In short, the structure is define like this:
1 2 3
struct GenericStructure {
double x,y,z;
}
Pretty simple.
Then I create a GenericStructure *temp = new GenericStructure(x,y,z);
and delete it with delete temp;
It fails because it's supposedly an illegal access. I was under the impression that a delete on a structure pointer always succeeds unless it doesn't point to the structure.
It's supposedly a write to adress 00000008?
Edit: So it appears to delete the structure after all, because in the debugger the value of the structure is indeed ??? after the error. For some reason delete wants to write as well?
Messing up my pointers? In such that they no longer point towards the structure? Unfortunately, I'm 100% sure that each pointer I try to delete points to a valid structure, because before deleting it I actually use one of its values.
That line is hideous. Also, it has a memory leak. Though I don't see how that would change loc_ptr, unless there is a "loc_ptr = " on the left side of it.
I don't know how exactly memory allocation works. I'm certain it varies between library implementations and operating systems. My point was that memory might be already free and reusable even if task manager says that you're still using it. Memory allocation may have a more complex process than "take from OS" and "give to OS". To write good code it is enough to trust the intelligence of whoever wrote your system. If you really want to know more, you'll have to find yourself an article on that somewhere. http://en.wikipedia.org/wiki/C_dynamic_memory_allocation#Implementations might be a good place to start.
Because I have to run calculations on a dynamic amount of structures.
I note you are not defining an assignment constructor?
I was making wrong use of an existing structure. I don't really understand your question, but there is a constructor available to initialize GenericStructure with given values x,y,z.
Just another question, say I have:
1 2 3 4 5
void method() {
GenericStructure temp = new GenericStructure();
submethod(&temp);
GenericStructure temp2 = new GenericStructure();
}
Does temp need to be deleted explicitly at the end of the method? And what about temp2?
Do they count as local variables, or is it always necessary to delete all local structures?
All memory allocated with new needs to be freed with delete. That is, there must be one delete for each new.
The pointer variables are local and the memory they use (4 bytes, for 32-bit pointers) is on the stack and is freed automatically. But the memory they point to is on the heap and is not automatically freed.
If you show your actual code, maybe we could help
I prefer to keep things general. So I can actually learn it myself and apply in several specific cases. In this case the vague questions and code examples led to a solution.