Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  1. who keeps this information?

  2. how is this information is kept?

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

like image 432
Eyal Avatar asked Apr 02 '11 20:04

Eyal


People also ask

What happens when memory leak in C?

Memory leak occurs when programmers create a memory in heap and forget to delete it. The consequences of memory leak is that it reduces the performance of the computer by reducing the amount of available memory.

Can you have memory leaks with smart pointers?

Smart pointers allow you to forget about manual allocation and can help avoid most memory leaks. On managed platforms, an object gets destroyed when there are no references to it.

What is a memory leak pointer?

A memory leak is when you dynamically allocate memory from the heap but never free it, possibly because you lost all references to it. They are related in that they are both situations relating to mismanaged pointers, especially regarding dynamically allocated memory.

Where are memory leaks found?

Where are memory leaks found? Explanation: Memory leaks happen when your code needs to consume memory in your application, which should be released after a given task is completed but isn't. Memory leaks occur when we are developing client-side reusable scripting objects.


2 Answers

  1. This information is kept in your program, in the variable a
  2. 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 an A
like image 71
Erik Avatar answered Nov 03 '22 04:11

Erik


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.

like image 28
Bo Persson Avatar answered Nov 03 '22 04:11

Bo Persson