Checking pointers

This is a discussion on Checking pointers within the C++ Programming forums, part of the General Programming Boards category; When you check to see that a pointer points to an existing object by using: Code: if (pointer) ... how ...

  1. #1
    Registered User johnnie2's Avatar
    Join Date
    Aug 2001
    Posts
    186

    Checking pointers

    When you check to see that a pointer points to an existing object by using:

    Code:
    if (pointer)
       ...
    how exactly does the program check the pointer's validity?
    "Optimal decisions, once made, do not need to be changed." - Robert Sedgewick, Algorithms in C

  2. #2
    Registered User
    Join Date
    Dec 2001
    Posts
    194
    That is the lazy way of checking to make sure the pointer is not pointing to NULL.
    NULL has a defined value of 0. But this only works if you make sure to set your pointers to NULL when you create them.
    Code:
    int * ptr = NULL;
    ptr = new int[100];
    if( ptr == NULL)
    {
       cout << "Calling new failed, out of memory";
       return;
    }
    // ptr is valid now.
    //do stuff
    delete [] ptr;
    //free the mem used

  3. #3
    Registered User johnnie2's Avatar
    Join Date
    Aug 2001
    Posts
    186
    Well, syntax aside, when you call something like if (ptr == NULL), how does the program know if ptr points to valid memory or not since a pointer will always point to some portion of memory?
    "Optimal decisions, once made, do not need to be changed." - Robert Sedgewick, Algorithms in C

  4. #4
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    Well, syntax aside, when you call something like if (ptr == NULL), how does the program know if ptr points to valid memory or not since a pointer will always point to some portion of memory?
    The pointer does point to a memory address, but C++ allows it to also point to 0 or NULL often to signify a problem or for initialisation purposes.

    If the pointer is NULL or 0 then the (ptr == NULL), expression will be (true). Its just a means to an end.
    Last edited by Fordy; 12-29-2001 at 01:35 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  2. Profiler Valgrind
    By afflictedd2 in forum C++ Programming
    Replies: 4
    Last Post: 07-18-2008, 09:38 AM
  3. Interpreter.c
    By moussa in forum C Programming
    Replies: 4
    Last Post: 05-28-2008, 05:59 PM
  4. Passing pointers between functions
    By heygirls_uk in forum C Programming
    Replies: 5
    Last Post: 01-09-2004, 05:58 PM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM

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