Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Jan 2005
    Thanked 1 Time in 1 Post

    Question How to check if a int* pointer is null? [C++]

    I have a class such as the following:
    class A
    	int* integer;
    	void Copy(const string&);
    	A(const string&);	// Constructor
    The function "Copy" can be used in two different instances:
    a) Creation of the class (Constructor)
    b) Assignment of int* integer

    In case (a) I need to assign the int* using calloc while in case (b) I simply want to change the size for the new assignment using realloc. Therefore my code works something like this:

    A::A(const string& sNumber)
    void A::Copy(const string& sNumber)
    	if (integer == NULL)
    		integer = (int*) calloc (size, sizeof(int));
    	else if (originalSize != size)
    		integer = (int*) realloc (integer, size * sizeof(int));
    Now this is causing me some issues, and I assume it is because of the way I am checking to see if my pointer (int* integer) is NULL or not ... I am trying to find out if (integer) has been assigned or not, if it already exists (not null) then just realloc, otherwise create it using calloc...

    Running this code generates the following error:
    0xC0000005: Access violation reading location 0xccccccc8

    When I look (watch) integer has a value of
    integer 0xcccccccc int *
    So, the pointer is NOT NULL, but I've never assigned it to anything yet...

    How do I check to see if I need to use calloc or realloc? How do I differentiate between both cases? Any ideas or help would be much appreciated.


  • #2
    Rockstar Coder
    Join Date
    Jun 2002
    Thanked 328 Times in 324 Posts
    That value 0xcccccccc is what is called a magic number. It is used in debugging to help you identify certain bugs in your program. What would happen in a non-debug version is that it would have whatever random value happened to be at that memory location when the program started.

    What you need to do is in your copy constructor, just set it to 0 before you call copy or create a base member initialization list to do it which would be better. If you have any other constructors in the class, you'd have to do something similar.
    Last edited by oracleguy; 05-28-2009 at 09:09 AM.


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts