NULL pointer increment in C

If I increment a pointer NULLto C, then what happens?

#include <stdio.h>

typedef struct
{
        int x;
        int y;
        int z;
}st;

int main(void)
{
        st *ptr = NULL;
        ptr++; //Incrementing null pointer 
        printf("%d\n", (int)ptr);
        return 0;
}

Conclusion:

12

Is this behavior undefined ? If not , then why ?

+4
source share
4 answers

The behavior is always undefined. You cannot store memory in NULL.

Pointer arithmetic is valid only in arrays, and you can set the pointer to the index of the array or one location after the final element. Note. I'm talking about setting a pointer here, not dereferencing it.

You can also set a pointer to a scalar and a scalar one after it.

.

+5

, undefined .

"" , a NULL post increment.

C11, §6.5.2.4

postfix ++ . ( 1 ). [....]

, § 6.5.5

, , . ( 1.)

P7,

[...] , , .

, P8,

, , . , P i - , (P)+N (, N+(P)) (P)-N ( N N) i+n -th i−n -th , . [....] , ; undefined.

+4

, , . , . :

printf("Test: %lu", sizeof(st));

Test: 12 . , *ptr, undefined.

0

, ptr ( ) struct st. , ptr++. 0 NULL. 12 (3 * sizeof(int)= 3 * 4 = 12).

0

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


All Articles