Are memory addresses duplicated on the heap?

Further explanation of the name issue is ok, let me explain my scenario.

I have a container of a list of pointers to several objects on the heap. Whenever a new object is created, the pointer to it is added to the list and whenever the object is deleted, its pointer is deleted. It is safe to say that all pointers in this list are always valid.

Many objects in the list contain pointers to other objects in the same list.

Before casting any of these pointers, I would like to use the CheckAgainstList(ptr*) function to make sure that one object points to another object in the same list and therefore does not point to the object that has since been deleted.

Get your tinfoil hats now, is this possible?

  • Object A has a pointer to object B with a memory address of 0x00988e50 .
  • Object B is deleted.
  • Object C is created and placed in the newly freed memory space 0x00988e50 .
  • CheckAgainstList(ptr*) returns true when we check the pointer, because the object C is in the list and is in the same memory address that was used by B.

Now we have a mistake, because A thinks she has a pointer to B, but B is gone, and C took his place to speak.

Is this potential error possible?

+4
source share
5 answers

Not only is this possible, it is very likely. A good memory allocator will try to reuse memory as often as possible in order to reduce fragmentation and bloating.

The problem you are trying to solve may fall under weak_ptr , which you can verify before using it.

+6
source

Yes, this error is quite possible.

Basically, what you do is pretty dangerous and will lead to errors pretty quickly. You might be better off using the link calculated by smart ptr. C ++ 11 includes std :: shared_ptr, which means you can use instead of a regular pointer. This way, the memory will not be freed until everything is done with it and the problems described by you are reduced.

Another option would be to look at all the other objects to see if they are referencing the deleted “Bs” and doing something like “null” from their pointers to a pointer that is now deleted.

+4
source

Memory addresses are reused - depending on the operating system. Otherwise, if the program makes many allocations and releases, more than in the RAM in the machine, it will not be able to continue.

In the end, the answer is more about the operating system and memory management scheme than C ++ itself. In the end, the most primitive thing that happens when allocating free (dynamic) memory is that the process (through a standard library function) calls a specific OS subroutine to allocate the requested amount of memory and return the address to the allocated memory.

+4
source

An error is more likely if you create only one type of object. But it is always possible.

+1
source

Yes it can happen. To prevent this, when you delete an object, go to the list and set any pointers to the remote object to indicate NULL.

0
source

All Articles