Thread: sizeof deferenced NULL pointer

  1. #1
    Registered User
    Join Date
    Feb 2022
    Location
    Canada, PEI
    Posts
    103

    sizeof deferenced NULL pointer

    I'm just wondering if this is a safe practice.

    Code:
    #include <stdio.h>
    
    int main(int argc, char ** argv) {
      int * i_ptr = NULL;
      fprintf(stdout, "size: %lld\n", sizeof(*i_ptr));//How safe is it to deference a NULL pointer here to get the data size?
      return 0;
    }
    My compiler has no problems with this but I'm guessing that dereferencing a NULL pointer is unsafe.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    sizeof is a compile time operation, not run-time.
    The actual initialised (or not) value of the pointer doesn't matter.

    The only dereferencing going on is the type to arrive at sizeof(int).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Feb 2022
    Location
    Canada, PEI
    Posts
    103
    Quote Originally Posted by Salem View Post
    sizeof is a compile time operation, not run-time.
    The actual initialised (or not) value of the pointer doesn't matter.

    The only dereferencing going on is the type to arrive at sizeof(int).
    So basically the compiler knows how big the pointer's data type is...

  4. #4
    Registered User
    Join Date
    Sep 2022
    Posts
    55
    Yes. The sizeof operation returns the size of a type. It is not related to the value of a variable. That's the reason why it works.
    FWIW There's an exception for the compile time evaluation. The size of a VLA can only be determined at run time. However, this doesn't apply for your example.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Null pointer vs uninitialized pointer
    By Abhishek Kumar in forum C++ Programming
    Replies: 23
    Last Post: 03-05-2014, 12:01 PM
  2. Does static initialization of pointer make it null pointer
    By Saurabh Mehta in forum C Programming
    Replies: 1
    Last Post: 11-23-2012, 12:05 AM
  3. sizeof pointer array
    By x77 in forum C Programming
    Replies: 5
    Last Post: 01-13-2009, 12:36 PM
  4. can't do sizeof(pointer)
    By ruffle in forum C Programming
    Replies: 8
    Last Post: 10-17-2005, 03:23 PM
  5. sizeof() function on a pointer to an array of a struct
    By tegwin in forum C++ Programming
    Replies: 7
    Last Post: 05-30-2004, 02:30 PM

Tags for this Thread