I saw a usage of the *
operator in front of the new operator. What does it do?
int x= *(new int);
I saw a usage of the *
operator in front of the new operator. What does it do?
int x= *(new int);
new int
is allocating memory.
By using defering operator * you are getting the value present at that memory location which would be garbage.
#include <iostream>
void main()
{
int x = *(new int);
std::cout << x;
system("pause");
}
But this will cause the memory leak.
The expression new int
creates an object of type int
in allocated memory and returns a pointer to said object. Because no initializer is specified, the object is default-initialized and therefore has an indeterminate value.
The expression int x = *(new int)
initializes x
with the value of the object referenced by the pointer returned by new int
. However, accessing indeterminate values in this way is undefined behaviour. Since standard imposes no requirements on the behaviour of programs containing undefined behaviour, any program containing the expression int x = *(new int)
could, in theory, do anything at all.
If your were to initialize the object created by the new
expression (e.g. new int()
), then x
would have whatever value you initialized the original object with. However, since you didn't store the pointer to the original object, there is no way to destroy the object using delete
, so you have a memory leak.