Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Other Discussions
  3. The Weird and The Wonderful
  4. NULL Checking and Defensive Programming

NULL Checking and Defensive Programming

Scheduled Pinned Locked Moved The Weird and The Wonderful
data-structuresperformancequestion
37 Posts 16 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P PIEBALDconsult

    But in that example you didn't set the pointer to NULL and you know it. A called method should not free something that was passed in, or if it's expected to, you'll need double indirection. Find a better example, that one's a coding horror on its own.

    N Offline
    N Offline
    Nemanja Trifunovic
    wrote on last edited by
    #26

    PIEBALDconsult wrote:

    But in that example you didn't set the pointer to NULL and you know it.

    Of course I did. Just after deleting it. I didn't set other pointers that point to the same object to NULL because it is impossible to do, and that was the point of my sample.

    PIEBALDconsult wrote:

    A called method should not free something that was passed in, or if it's expected to, you'll need double indirection. Find a better example, that one's a coding horror on its own.

    Of course it is a horror - and you can't protect from such horrors by checking if a pointer is NULL. That's all I am trying to point here.

    Programming Blog utf8-cpp

    1 Reply Last reply
    0
    • D Dave Kreskowiak

      To chime in with the biggest noob problem, at least in the VB.NET forum, what's the default for a newly created, but uninitialized pointer?? I haven't written any C++ code in quite a while, but I believe it was 0.

      A guide to posting questions on CodeProject[^]
      Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
           2006, 2007, 2008

      N Offline
      N Offline
      Nemanja Trifunovic
      wrote on last edited by
      #27

      Dave Kreskowiak wrote:

      what's the default for a newly created, but uninitialized pointer??

      Whatever it happens to be in that memory location at the time a pointer is defined :)

      Programming Blog utf8-cpp

      1 Reply Last reply
      0
      • D Dave Kreskowiak

        To chime in with the biggest noob problem, at least in the VB.NET forum, what's the default for a newly created, but uninitialized pointer?? I haven't written any C++ code in quite a while, but I believe it was 0.

        A guide to posting questions on CodeProject[^]
        Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
             2006, 2007, 2008

        P Offline
        P Offline
        PIEBALDconsult
        wrote on last edited by
        #28

        I didn't see it in the spec and I don't have an up-to-date C++ compiler handy. But I expect that if it isn't NULL already it soon will be.

        N 1 Reply Last reply
        0
        • P PIEBALDconsult

          I didn't see it in the spec and I don't have an up-to-date C++ compiler handy. But I expect that if it isn't NULL already it soon will be.

          N Offline
          N Offline
          Nemanja Trifunovic
          wrote on last edited by
          #29

          PIEBALDconsult wrote:

          But I expect that if it isn't NULL already it soon will be.

          No it won't. The new standard is ready to be adopted and there is nothing about it that would mandate such behavior. None of the compilers I used recently (MS and GNU) automatically initialize local variables.

          Programming Blog utf8-cpp

          1 Reply Last reply
          0
          • L Lost User

            Nemanja Trifunovic wrote:

            There is no such thing as a "NULL pointer exception" - there is "access violation"

            Nemanja, Come on man I know your not really that pedantic about verbiage. Call it whatever you want, "Access Violation" is simply an error title. Now your just trying to be argumentative. I'll call it segmentation fault[^] from now on just to get under your skin.

            Nemanja Trifunovic wrote:

            if you follow your rules you may still very easily run into it

            First off let me say that I have respect for both you and your philosophy. I can only hope to recieve the same. But unfortunately I have a partially opposing view. There are many techniques to making software more robust. Assigning pointers to NULL and checking for NULL is only one of them and many companies practice it as can be seen in both Microsoft DDK and Platform SDK samples. Logically from a mathematical statistics standpoint any technique which reduces the chance of accessing an invalid memory address would be beneficial to the software. Magic Number[^] assignment/checking is used by all major software vendors.. Apple, Microsoft and IBM etcetera. Recognize any of these? 0xCDCDCDCD 0xBAADF00D 0xCCCCCCCC Initializing a pointer to NULL to denote an invalid memory address is the same magic number technique. It assists the programmer with validating pointers and most certainly assists with making software more robust. I am not interested in arguing the point anymore. I fully expect you to reject my assertions and you are within your rights to do so. Let us agree that we disagree and leave it at that. Best Wishes, -David Delaune

            N Offline
            N Offline
            Nemanja Trifunovic
            wrote on last edited by
            #30

            Randor wrote:

            Come on man I know your not really that pedantic about verbiage. Call it whatever you want, "Access Violation" is simply an error title. Now your just trying to be argumentative. I'll call it segmentation fault[^] from now on just to get under your skin.

            It is more than just verbiage. By following your rules (which btw really make sense in C90 where you have to declare all variables in the beginning of the function) you will indeed never hit a "null pointer segfault" but segfaults happen on any invalid pointer, not just NULL.

            Randor wrote:

            There are many techniques to making software more robust. Assigning pointers to NULL and checking for NULL is only one of them

            At least now we are not claiming that by following these two simple rules we will never segfault :)

            Randor wrote:

            Initializing a pointer to NULL to denote an invalid memory address is the same magic number technique. It assists the programmer with validating pointers and most certainly assists with making software more robust.

            And guess what? I agree. If you initialize a pointer to NULL, and then go to different code paths in which it may or may not be set to point to a valid object, checking it for NULL makes a perfect sense. However, this thread is about a guy who inserts NULL checks all around the code in the hope it would make it more robust. Well, it won't. If there is a bug in the code, chances are it will not be caught by a NULL check.

            Programming Blog utf8-cpp

            1 Reply Last reply
            0
            • P PIEBALDconsult

              Nemanja Trifunovic wrote:

              NULL only if you explicitly set it to NULL - an unitialized pointer is not going to be NULL

              C99 and C# initialize pointers (references) to NULL. Retraction: OK, I misread the C99 spec; I saw, "-- if it has pointer type, it is initialized to a null pointer;" without reading the lead-in, which indicates that that's only true for static, not automatic, storage. :sigh: If you don't assign NULL to pointer variables when freed then you're on your own.

              N Offline
              N Offline
              Nemanja Trifunovic
              wrote on last edited by
              #31

              PIEBALDconsult wrote:

              C99 and C# initialize pointers (references) to NULL

              Could you give a link to a reference for C99? I admit I have never heard of this.

              Programming Blog utf8-cpp

              1 Reply Last reply
              0
              • S Swinefeaster

                I just received a crazy lecture from one of my superiors when I tried to introduce NULL pointer checks in the code. Apparently, he says, "Pointers should never be NULL" and "Checking pointers for NULL throughout the code eats too many cpu cycles and seriously degrades performance", "It's better just to crash and provide a stack dump." Am I on crack?

                S Offline
                S Offline
                supercat9
                wrote on last edited by
                #32

                Pointers should be explicitly checked for null if there is a realistic scenario by which they could be null. For example, ptr=malloc(1024); will set ptr to null if the system cann't allocate 1024 bytes for it. If the program isn't allocating much memory, such a scenario may be unlikely but not unrealistic. On the other hand, in something like:

                {
                int arr[5];
                int *p;
                int i;

                p=arr;
                for (i=0; i<5; i++)
                *p++ = i;
                }

                there is no realistic way that p is ever going to be null. It simply can't happen.

                P 1 Reply Last reply
                0
                • S supercat9

                  Pointers should be explicitly checked for null if there is a realistic scenario by which they could be null. For example, ptr=malloc(1024); will set ptr to null if the system cann't allocate 1024 bytes for it. If the program isn't allocating much memory, such a scenario may be unlikely but not unrealistic. On the other hand, in something like:

                  {
                  int arr[5];
                  int *p;
                  int i;

                  p=arr;
                  for (i=0; i<5; i++)
                  *p++ = i;
                  }

                  there is no realistic way that p is ever going to be null. It simply can't happen.

                  P Offline
                  P Offline
                  PIEBALDconsult
                  wrote on last edited by
                  #33

                  I think it's more a question of, if you write a function (perhaps a library function) that takes one or more pointers, do you check them for null or let them blow up? And why?

                  S 1 Reply Last reply
                  0
                  • S Swinefeaster

                    I just received a crazy lecture from one of my superiors when I tried to introduce NULL pointer checks in the code. Apparently, he says, "Pointers should never be NULL" and "Checking pointers for NULL throughout the code eats too many cpu cycles and seriously degrades performance", "It's better just to crash and provide a stack dump." Am I on crack?

                    M Offline
                    M Offline
                    mbcvamsidhar
                    wrote on last edited by
                    #34

                    Use Assertions as it will be useful to chack for NULL pointers.Debug.Assertin C#

                    Thanks and Rgds, VamsiDhar.MBC SoftwareEngineer.

                    1 Reply Last reply
                    0
                    • P PIEBALDconsult

                      I think it's more a question of, if you write a function (perhaps a library function) that takes one or more pointers, do you check them for null or let them blow up? And why?

                      S Offline
                      S Offline
                      supercat9
                      wrote on last edited by
                      #35

                      PIEBALDconsult wrote:

                      I think it's more a question of, if you write a function (perhaps a library function) that takes one or more pointers, do you check them for null or let them blow up? And why?

                      IMHO, the biggest questions would be:

                      1. Is the operation in the null-pointer situation defined by the interface standard?
                      2. Would the null-pointer situation have a logical meaning (e.g. it may be useful for a function that reads data from a stream to have an option to simply throw away some data; allowing the function to take a null pointer for such usage may be more elegant than requiring the use of a separate function)?
                      3. Are there any circumstances that could case a null pointer to be passed in accidentally?
                      4. How would the probable consequence of passing in a null pointer compare with the best result one could achieve?

                      Incidentally, I found myself annoyed at the design of some TCP libraries which returned the same sort of failure code when a non-blocking write attempt was done on a port whose buffer was full, as when such an attempt was performed on a port that was closed. The full-buffer case needs to be easily distinguishable from the closed-port case, since one will want to wait in the former case but not the latter. In my own libraries, I allow a write to a closed port to immediately return 'success', but then check whether the port is actually open. If the port closed unexpectedly, the data I'm sending will vanish into the aether, but the program won't crash. I may not know how much data vanished in the aether, but oftentimes (1) it won't matter, and (2) it may be impossible to know for certain if some packets gets sent but never acked. A closed port isn't quite the same thing as a null pointer, but I think some of the philosophical arguments are similar.

                      1 Reply Last reply
                      0
                      • S Swinefeaster

                        I just received a crazy lecture from one of my superiors when I tried to introduce NULL pointer checks in the code. Apparently, he says, "Pointers should never be NULL" and "Checking pointers for NULL throughout the code eats too many cpu cycles and seriously degrades performance", "It's better just to crash and provide a stack dump." Am I on crack?

                        Y Offline
                        Y Offline
                        Yuriy Levytskyy
                        wrote on last edited by
                        #36

                        You are using pointers???

                        1 Reply Last reply
                        0
                        • S Swinefeaster

                          I just received a crazy lecture from one of my superiors when I tried to introduce NULL pointer checks in the code. Apparently, he says, "Pointers should never be NULL" and "Checking pointers for NULL throughout the code eats too many cpu cycles and seriously degrades performance", "It's better just to crash and provide a stack dump." Am I on crack?

                          W Offline
                          W Offline
                          Wenff
                          wrote on last edited by
                          #37

                          WTF!!!???? :omg: I think I might be close to speechless. Has the man never had a blue screen of death and gotten annoyed? Never thought I'd hear of some genius campaigning for application failure...

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups