Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing NULL pointer in C

If I incrementing NULL pointer in 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;
}

Output:

12

Is it undefined behavior? If No, then Why?

like image 621
msc Avatar asked Apr 28 '17 06:04

msc


2 Answers

The behaviour is always undefined. You can never own the memory at NULL.

Pointer arithmetic is only valid within arrays, and you can set a pointer to an index of the array or one location beyond 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 one past that scalar.

You can't use pointer arithmetic to traverse other memory that you own.

like image 143
Bathsheba Avatar answered Nov 07 '22 09:11

Bathsheba


Yes, it causes undefined behavior.

Any operator needs a "valid" operand, a NULL is not one for the post increment operator.

Quoting C11, chapter §6.5.2.4

The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). [....]

and related to additive operators, §6.5.6

For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to a complete object type and the other shall have integer type. (Incrementing is equivalent to adding 1.)

then, P7,

[...] a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

and, P8,

If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i+n-th and i−n-th elements of the array object, provided they exist. [....] If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

like image 5
Sourav Ghosh Avatar answered Nov 07 '22 08:11

Sourav Ghosh