-1

Suppose i create a new float;

float *pointer = new float;

now i delete this pointer.

 delete pointer;

Now can i create a new float at the same memory location the pointer was pointing to ?

float *pointer1 = new float;
Summit
  • 2,112
  • 2
  • 12
  • 36
  • Long answer short, its the OS which handles the memory. So, if you try to do it explicitly (which I am guessing you haven't), you will face judgement (read SIGSEGV core dumped)! – kesarling He-Him Sep 25 '20 at 04:12
  • The probability of reuse is reasonably high, but no guarantees. The runtime may hold onto that block of memory after it's deleted and serve it right up again. Even more fun, the compiler may see you giving the allocation back and then grabbing a new one of the same size and shape and do some [As If Rule](https://en.cppreference.com/w/cpp/language/as_if) magic and optimize out the `delete` and `new`. – user4581301 Sep 25 '20 at 04:17
  • 1
    You can use placement new to control where the new float is created. You can read about it [here](https://stackoverflow.com/questions/222557/what-uses-are-there-for-placement-new). It really depends on what you are trying to do though. If its just one float you may as well just use a float variable i.e. not allocated on the heap. – Paul Rooney Sep 25 '20 at 04:19
  • No, it do not use same memory location – Build Succeeded Sep 25 '20 at 05:57
  • @BuildSucceeded sure it can. You can't get the same address if it is still in use, but If the storage has been returned to the freestore, the freestore could give it right back again the next time the program asks. – user4581301 Sep 25 '20 at 14:55

1 Answers1

3

Is it possible to create a variable at an assigned address location

No. The language implementation is responsible for choosing the address of all variables.

It is possible to create a dynamic object at an address, as long as that address satisfies certain preconditions. In particular, the memory has to be allocated, it must not be used by any non-trivial object, and the address must satisfy the alignment of the type. The syntax for creating an object at an address is called placement-new.

now i delete this pointer.

Now can i create a new float at the same memory location the pointer was pointing to ?

You have deallocated the memory, so you may not create an object there.

There is no standard way to allocate a specific address, and if the address is something that may be returned by by the global allocator, then allocating such address using system specific means would probably break the global allocator.

TL;DR You cannot do that explicitly. However if you do new float immediately after that deletion, then it is possible and in some cases likely that you get the same address.

eerorika
  • 232,697
  • 12
  • 197
  • 326