C++ - Memory leaks: where is the pointer (meta) information stored?
This is a basic question of which I can't find any answer.
Given the next code, a memory leak will occur:
int main(){
A* a = new A();
// 1
}
//2
Lets say that a got the value 1000. That is, the address 1000 on the heap is now taken by an A object. On 1, a == 1000 and on 2 a is out of scope. But some information is missing.
In real life, the address 1000 is the address of a开发者_开发百科 byte in the memory. This byte does not have the information that it stores a valuable information.
My questions:
who keeps this information?
how is this information is kept?
which component "knows" from where to where the pointer a points to? How can the computer know that a points to sizeof(A) bytes?
Thanks!
- This information is kept in your program, in the variable
a
- The compiler knows this while compiling. Run-time only the allocator knows that "at this particular address
sizeof(A)
bytes are reserved" - and you can't use that info, you're simply expected to treat these bytes as if they contained anA
The language standard doesn't say.
All we know is that if we do delete a
, the memory is released again.
There are several options, like allocating everything that is sizeof(a) from a certain memory pool with addresses 1000 to 1000+x. Or someone (the language runtime or the OS) can keep at table somewhere. Or something else.
Typically new and delete operators are implemented on top of malloc and free, though this detail is unspecified. malloc and free both point to a data structure which tracks which regions of memory are allocated, which are not, and how big each region is. Knuth's Art of Computer Programming Vol 1 has a pretty good description of a few allocator designs.
- The memory address is stored in the variable
a
. - It's simply kept as a value on the stack like any other local variable. Just a plain old number that refers to a memory location that stores an A object.
- The compiler knows that the type of
a
isA*
. So it knows that the object at the location held ina
should be an A object. That's why you get problems if you have other objects at that location. The generated machine code will act as though an A object is there, so if there isn't (perhaps there is a derived class there) then it must be built to be able to survive it (virtual function tables in the case of a derived class).
Once a local pointer goes out of scope, it will be taken off the stack. If that was the only pointer to the object on the heap, then you've lost any way to delete it. That's why you get a memory leak. Suddenly you have no idea where the object is any more because you lost your only pointer.
精彩评论