null pointer dereference

This is a discussion on null pointer dereference within the C Programming forums, part of the General Programming Boards category; I was looking at the container_of macro, and this piece of code confuses me a bit: Code: const typeof( ((type ...

  1. #1
    Registered User
    Join Date
    Jul 2010
    Posts
    26

    null pointer dereference

    I was looking at the container_of macro, and this piece of code confuses me a bit:

    Code:
     const typeof( ((type *)0)->member ) *__mptr = (ptr);
    Why is it legal to cast 0 (null pointer?) into some (type *) and then deference it to get the structure's member field? Shouldn't it cause some kind of segmentation violation?

  2. #2
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,160
    Quote Originally Posted by qwertylurker View Post
    I was looking at the container_of macro, and this piece of code confuses me a bit:

    Code:
     const typeof( ((type *)0)->member ) *__mptr = (ptr);
    Why is it legal to cast 0 (null pointer?) into some (type *) and then deference it to get the structure's member field? Shouldn't it cause some kind of segmentation violation?
    No actual dereferencing occurs. The -> operator is only being used in this case to name a member of 'type' for the typeof() operator to operate on.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  3. #3
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    3,815
    Yikes. That is as ugly as old Yog.

    Assuming `typeof' is the GCC variation, the line is never compiled, executed, or even "seen" by the generation side of the compiler.

    Soma

  4. #4
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    typeof is gcc extension. I think it's just like sizeof(*p) . Where p is NULL. Actual deferencing is never made.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. crashing program, help
    By xniinja in forum Windows Programming
    Replies: 1
    Last Post: 07-07-2010, 03:57 PM
  2. Replies: 7
    Last Post: 05-17-2010, 04:09 AM
  3. New string functions
    By Elysia in forum C Programming
    Replies: 11
    Last Post: 03-28-2009, 05:03 AM
  4. . . . . . . - . . . - -
    By The Brain in forum C++ Programming
    Replies: 17
    Last Post: 05-17-2005, 04:01 AM
  5. BST/Red and Black Tree
    By ghettoman in forum C++ Programming
    Replies: 0
    Last Post: 10-24-2001, 10:45 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21