View Full Version : How to check if a int* pointer is null? [C++]

05-28-2009, 07:43 AM
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.


05-28-2009, 09:04 AM
That value 0xcccccccc is what is called a magic number (http://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_debug_values). 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.