Thread: Dereference a member of NULL ?

  1. #1
    Registered User
    Join Date
    May 2009
    Location
    Boston
    Posts
    12

    Dereference a member of NULL ?

    The following code seems to work, but I don't understand why.
    The line:
    Code:
    zip = &dog->next;
    Looks to me like it is de-referencing 'next' member of NULL, which doesn't make a whole lot of sense. Is that what is going on, or I am misunderstanding what is going on here? If so, is that well defined?

    Thank you,
    Kyle

    Code:
    #include <stdio.h>
    
    struct foo {
        int value;
        struct foo * next;
    };
    
    int main() {
        struct foo baz;
        struct foo *dog;
        struct foo **zip;
        baz.next = NULL;
        zip = &baz.next;
        dog = *zip;
        zip = &dog->next;
        return(0);
    }

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    No, the value in *zip will be NULL, but it's not dereferencing NULL. Obviously, if you have code like **zip somewhere, it would access at NULL.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    May 2009
    Location
    Boston
    Posts
    12
    So what is it doing then?
    dog = Pointer to NULL
    so dog->next is....?

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Yes, sorry, didn't read the code very well. With dog = *zip, then dog == NULL, and dog->next is invalid. However, since you are using &dog->next, the compiler may simply add the offset of next to NULL, so whilst it's undefined behaviour, it may not crash.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Registered User
    Join Date
    May 2009
    Location
    Boston
    Posts
    12
    Ah, that makes sense to me! Thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. New string functions
    By Elysia in forum C Programming
    Replies: 11
    Last Post: 03-28-2009, 05:03 AM
  2. "is not a member of 'IDirect3D9'" error
    By The Prophet in forum C Programming
    Replies: 2
    Last Post: 07-02-2005, 09:32 PM
  3. . . . . . . - . . . - -
    By The Brain in forum C++ Programming
    Replies: 17
    Last Post: 05-17-2005, 04:01 AM
  4. Help with yacc/compiler design/seg fault
    By trippeer in forum C Programming
    Replies: 1
    Last Post: 04-08-2005, 03:43 AM
  5. button 'message'
    By psychopath in forum Windows Programming
    Replies: 12
    Last Post: 04-18-2004, 09:57 AM