Address returned by new operator in C is unique throughout the process? What if someone delete the memory, can same address be returned by new again?
Best Regards, Chandan
CodePudding user response:
The return value of new
is not guaranteed to be unique throughout your processes' runtime. The only real guarantees you get are that the value is non-null, aligned to the requested type, and is at least large enough to fit the requested type (or, you get a std::bad_alloc
). You can likely observe this on your own system with the following snippet:
int main()
{
for (int i = 0; i < 10; i )
{
int *p = new int;
std::cout << reinterpret_cast<void *>(p) << std::endl;
delete p;
}
}
/*
Example output:
0x2576e70
0x2576e70
...
*/
Of course, an implementation may opt to give you unique addresses every time. However, I suspect no common implementation would provide this by default.
CodePudding user response:
C standard guarantees comparison and pointer arithmetics of two pointers to be correct only if both pointers refer to locations in storage of same object or to elements of same array. If the old object was deleted and new was created in such way that pointer refers to a memory location in its storage, the result of comparison is undefined as well as result of dereferencing such pointer.
- You had created an object
A
of typeT
and a pointer to itT* pA
.
Possible follow ups:
You destroyed
A
by callingdelete pA
. Value of pA didn't change.You had created an object
B
of typeT
and a pointer to itB* pB
.You compare pA which contains address in storage of defunct object A and pB which contains address in storage of object B.
Result of comparison is (undefined) true, because memory was re-used, or
Result of comparison is (undefined) false, because {implementation defined reasons}.
But another way if may fail on some platforms where paged memory is swapped out.
You had created an object
B
of typeT
and a pointer to itB* pB
.You compare
pA
which contains address in storage of still existing objectA
andpB
which contains address in storage of objectB
.Result of comparison is (undefined) true, because memory was swapped, or
Result of comparison is (undefined) false, because objects aren't in concurrent page or are in same page.
For that reason, compilers on systems with such possibility implement a pointer as a structure with additional information, not as mere address, to track where objects are currently stored.
There is no guarantees that the value of a correct pointer to dynamically or automatically created storage would be unique or not. The nature of computer's architecture suggests that memory would be reused as you have limited resources.
PS. You still can use pointers to identify separate objects if they are elements of same array, including case where they were created by placement-new in same array. It's a valid strategy for a memory pool, but creations and deletion of objects have to be tracked somehow to identify if a particular object is still "alive".