0

I saw a usage of the * operator in front of the new operator. What does it do?

int x= *(new int);
CinCout
  • 9,486
  • 12
  • 49
  • 67
UBA
  • 81
  • 6

2 Answers2

4
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.

Sumeet
  • 779
  • 6
  • 20
1

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.

Joseph Thomson
  • 9,888
  • 1
  • 34
  • 38
  • Technically, it just produces a reference to the new object. E.g. consider `int &r = *(new int);` –  Apr 03 '17 at 08:40
  • @Hurkyl Thanks. You are right. The undefined behaviour will only be invoked when the value of `*(new int)` is evaluated. I have updated my answer, so it should be technically correct now. – Joseph Thomson Apr 03 '17 at 14:18
  • @Hurkyl, in that case you are forced to use `delete &r` once you don't need the allocated object anymore. Or you'll continue to have a memory leak. – Luis Colorado Apr 04 '17 at 15:00