cpointersundefined-behaviorinvalid-pointer

Is fetching the value of an invalid pointer undefined or implementation defined behaviour in C?


Fetching the value of an invalid pointer is an implementation defined behavior in C++ according to this. Now consider the following C program:

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    int* p=(int*)malloc(sizeof(int));
    *p=3;
    printf("%d\n",*p);
    printf("%p\n",(void*)p);
    free(p);
    printf("%p\n",(void*)p); // Is this undefined or implementation defined in behaviour C? 
}

But is the behaviour same in C also? Is the behaviour of the above C program undefined or implementation defined? What does the C99/C11 standard say about this? Please tell me if the behaviour is different in C99 & C11.


Solution

  • Expanding on Andrew Henle's answer:

    From the C99 Standard, 6.2.4:

    An object has a storage duration that determines its lifetime. There are three storage durations: static, automatic, and allocated. Allocated storage is described in 7.20.3. […] The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

    Then in 7.20.3.2: the standard goes on describing malloc(), calloc() and free(), mentioning that

    The free function causes the space pointed to by ptr to be deallocated.

    In 3.17.2:

    indeterminate value

    either an unspecified value or a trap representation

    In 6.2.6.1.5:

    Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. […] Such a representation is called a trap representation.

    Since the pointer becomes indeterminate, and an indeterminate value can be a trap representation, and you have a variable which is an lvalue, and reading an lvalue trap representation is undefined, therefore yes, the behavior may be undefined.