What happens if you search for a "new int"?

Is the following safe?

*(new int);

I get a conclusion like 0.

+4
source share
4 answers

Its undefined because you are reading an object with an undefined value. The expression new int()uses zero initialization, guaranteeing a zero value, and new int(without parentheses) uses the default initialization, giving you an undefined value. This is actually the same as saying:

int x;              // not initialised
cout << x << '\n';  // undefined value

But, in addition, since you are immediately looking for a pointer to the selected object and do not store the pointer anywhere, this means a memory leak.

, ; , :

int& x = *(new int);  // x is an alias for a nameless new int of undefined value
x = 42;
cout << x << '\n';
delete &x;
+11

undefined (UB), , ++ 14 undefined, , new , ++ 14 5.3.4 17, ( ):

, (8.5). [: , . -end note]

int , 7 8.5, :

T :

- T (, cv-) ( 9), (12.1) T ( , T (13.3), , );

- T - , ;

- , .

8.5 , undefined:

, . , , , , (5.17). [. , . 3.6.2. - , undefined,

char, .

:

int& x = *(new int); 

, undefined. , , undefined , . , 8.5.3 , , :

"cv1 T1" "cv2 T2" :

- lvalue

     
  

- lvalue ( -), "cv1 T1" - "cv2 T2"

  

:

lvalue [...] [: lvalue-to-rvalue (4.1), (4.2) - (4.3) , lvalues. -end note]

+7

, "" int: , , , .

undefined. .

, . - , , :

int & ir = * ( new int ) = 0;
delete & ir;
+2

, . , . , , .

, :

int *p = new int;       // ie this is a local variable (ptr) that points 
                        // to a heap-allocated block

, , , undefined . IE 0x00, 0xFFFFFFFF, (aka RIP register Intel) . .

int *p = new int;
std::cout << *p;    // Very, bad. Undefined behavior.

, Valgrind ASan , .

, :

int *p = new int;
*p = 0;

Background information: This particular way of writing a specification is very useful for performance because it is prohibitively expensive to implement an alternative.

Please note that according to standard links, initialization is sometimes cheap, so you can do the following:

// at the file scope
int global1;          // zero-initialized
int global2 = 1;      // explicitly initialized

void f()
{
    std::cout << global1;
}

These things are included in executable sections (.bss and .data) and are initialized by the bootloader.

+1
source

All Articles