Assessing the state containing a unified pointer is UB, but can it fail?

Somewhere on the forums, I came across this:

Any attempt to evaluate an uninitialized pointer variable
invokes undefined behavior. For example:

int *ptr; /* uninitialized */
if (ptr == NULL) ...; /* undefined behavior */

What is meant here? This means that if I ONLY write:

if(ptr==NULL){int t;};

Is this statement already UB? What for? I'm not looking for a pointer correctly? (I noticed there might be a terminological problem, UB in this case, I mentioned: will my code crash ONLY because of an if check?)

+2
source share
7 answers

Using unified variables causes undefined behavior . It doesn't matter if it is a pointer or not.

int i;
int j = 7 * i;

undefined. , "undefined" , , , , .


:

int *ptr;
if (ptr == NULL) { int i = 0; /* this line does nothing at all */ }

ptr , - , NULL. , , , ptr NULL. , , , - , undefined.

+3

. , :

int a;
if (a == 3){int t;}

a ; , undefined. , . , segfault

+2

C99 , undefined Annex J.2 undefined:

, (6.2.4, 6.7.8, 6.8).

, 6.5.2.5 , 17, :

, goto , , p , , undefined.

undefined :

,

, :

undefined , , ( ), ( ).

+2

, C99 undefined. , . , .

int *pi; if (pi == NULL){} . , . , , NavN float, , . , . , ?.

+1

- undefined - , . , , , .

, :

#include <stdio.h>

void test()
{
    int *ptr;
    printf("ptr is %p\n", ptr);
}

void another_test()
{
    test();
}

int main()
{
    test();
    test();
    another_test();
    test();
    return 0;
}

test() , , "ptr" . , , , , , "ptr" , .

, , :

ptr is 0x400490
ptr is 0x400490
ptr is 0x400575
ptr is 0x400585

, ,

#include <stdio.h>

void test()
{
    int *ptr;
    printf("ptr is %p\n", ptr);
}

void something_different()
{
    int *not_ptr_or_is_it = (int*)0xdeadbeef;
}

int main()
{
    test();
    test();
    something_different();
    test();
    return 0;
}

undefined, . undefined, , , , , C

ptr is 0x400490
ptr is 0x400490
ptr is 0xdeadbeef
0

, rvalue . , - , 0 1.

, , , . , , , , , .

, "" Undefined, , UB, , , , , . "" , , , , , .

0

, segfault. . , - , . . :

. .

UB. , . NULL. , if (ptr == NULL) true.

IT NOT NOT CRASH. , 0 0xFFFFFFFF 32- x86 ARMv6. .

0..0xFFFFFFFF 0xFFFFFFFF00000000..0xFFFFFFFFFFFFFFFF amd64. , .
, .

I challenge commentators and downvoters to show the platform and the significance of where it crashes. Until then, I can probably survive in a few negative moments.

There is also a link to SO mapping the trap which also indicates that it will not work.

-2
source

Source: https://habr.com/ru/post/1532256/


All Articles