0

I'm confused about how null pointer access a structure member in c language.

#include <stdio.h>

struct A
{
    int i;
    char str[30];
};

int main()
{
    struct A *p = NULL;

    printf("accessing str with null pointer %d\n", p->str);
    printf("accessing i with null pointer %d\n", p->i);
    printf("accessing str[0] with null pointer %d\n", p->str[0]);

    return 0;
}

In above example, only first printf is executing. Other printf are crashing the program. I thought all of them would crash the program. but why p->str(array member) isn't causing any problem? From my search I found those questions NULL pointer able to access class member function and Accessing class members on a NULL pointer which is helpful but questions are related with member function. Can someone help me to understand, how null pointer access work for member variables (array and non-array).

Community
  • 1
  • 1
  • 1
    What happens is you change `printf("accessing str with null pointer %d\n", p->str);` to `printf("accessing str with null pointer %s\n", p->str);` since you are trying to output a string and not an integer? – NathanOliver Dec 02 '15 at 17:22
  • 1
    Duplicate? C and C++ are not the same I'd say. Here it is the printf function and the specifier that influence the result. I would not close that question. – Ely Dec 02 '15 at 17:26
  • Undefined Behavior is Undefined Behavior – bolov Dec 02 '15 at 17:26
  • my intention isn't to print the string value but to access p->str. str is a array. so %d should print the address of array. but since p is null it should not (?) able to do that? right? – Masud Parves Bhuiyan Dec 02 '15 at 17:27
  • 1
    The "value" of `p->str` that is passed to printf() is actually the pointer to `str`'s first element (due to implicit conversion of array to pointer). This address is calculated directly by adding an offset to `p`, without the need to *dereference* it. On the other hand, displaying `i` or the array contents dereferences the pointer. – Medinoc Dec 02 '15 at 17:28
  • @Elyasin the whole discussion about what happens when you pass... is moot. The moment you write `p->whatever` or `*p` where `p` is NULL you get Undefined Behavor – bolov Dec 02 '15 at 17:30
  • 1
    In fact, it's exactly the same kind of behavior one would get with `printf("Address-of through null pointer: %p\n", &p->i);` (only with the correct format specifier, this time). In either case, the pointer is not dereferenced because all it takes is adding the variable's offset to it. – Medinoc Dec 02 '15 at 17:33
  • @Medinoc I get your point. thanks for your help. – Masud Parves Bhuiyan Dec 02 '15 at 17:38
  • Last thing: I'd like to point out that the `offsetof` macro does precisely this: Use a null pointer to the structure, get the address of its member, and return this as the offset. – Medinoc Dec 02 '15 at 17:42

0 Answers0