Categories
askquestion

Check for pointer definedness in C++

Check for pointer definedness in C++

Ask Question

Asked
11 years, 1 month ago

Active
8 years ago

Viewed
15k times

.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}

4

How do I check if a variable, specifically a pointer, is defined in C++? Suppose I have a class:

class MyClass {
public:

MyClass();

~MyClass() {
delete pointer; // if defined!
}

initializePointer() {
pointer = new OtherClass();
}

private:

OtherClass* pointer;

};

c++ pointers

share|improve this question

edited Feb 5 ’12 at 19:02

Hubert Kario

14.6k33 gold badges1919 silver badges3636 bronze badges

asked Dec 19 ’08 at 18:05

tunnuztunnuz

19.8k2727 gold badges8181 silver badges122122 bronze badges

1

Can you please edit the title? it sounds like you want to check whether a variable is defined (literally). But it looks like you want to check whether a variable contains a defined value.

– Johannes Schaub – litb
Dec 19 ’08 at 18:12

add a comment
 | 

8 Answers
8

active

oldest

votes

22

Why worry about checking for the pointers value? Just initialize it to a null pointer value and then just call delete on it. delete on a null pointer does nothing (the standard guarantees it).

class MyClass {
public:

MyClass():pointer(0) { }

~MyClass() {
delete pointer;
pointer = 0;
}

initializePointer() {
pointer = new OtherClass();
}

private:

OtherClass* pointer;

};

And everytime you call delete on it, you should set the pointer to a null pointer value. Then you are all fine.

share|improve this answer

answered Dec 19 ’08 at 18:14

Johannes Schaub – litbJohannes Schaub – litb

440k107107 gold badges813813 silver badges11301130 bronze badges

I usually compile with all warnings treated as errors. I got compilation errors for deleting 0-valued pointers.

– tunnuz
Dec 19 ’08 at 18:21

How does the compiler know that a pointer will be zero at run-time?

– James Curran
Dec 19 ’08 at 18:27

Tommaso, that sounds naughty. i would also like to know how the compiler can know at compile-time what the pointer contains at runtime.

– Johannes Schaub – litb
Dec 19 ’08 at 18:36

why bother setting it to 0 after you delete it. After an objects destructor is called it doesn’t exists anymore. Therefore you don’t have to worry about anything else referencing it.

– Greg Rogers
Dec 19 ’08 at 18:40

1

@Greg Rogers: while it does not help here, it does not hurt either. In other situations, where instead of the destructor the delete takes place in another part of the code, setting the pointer to 0 will avoid a double delete through this variable (not through other pointers).

– David Rodríguez – dribeas
Dec 19 ’08 at 18:41

 | 
show 4 more comments

8

I tend to initialize my pointer values to NULL on object construction. This allows a check against NULL to see if the pointer variable is defined.

share|improve this answer

answered Dec 19 ’08 at 18:06

Gabriel IsenbergGabriel Isenberg

22.1k44 gold badges3232 silver badges5757 bronze badges

I agree except that you should use 0 not NULL. see research.att.com/~bs/bs_faq2.html#null

– Douglas Leeder
Dec 19 ’08 at 18:25

Or, in C++0x, you should use nullptr.

– Max Lybbert
Dec 19 ’08 at 20:36

1

I agree, though “I tend to” makes it sound like “it’s advisable to breathe from time to time”.

– peterchen
Dec 20 ’08 at 0:07

add a comment
 | 

6

In addition to checking for 0 (NULL), one solution would be to refactor your code so you force the pointer to always be valid. This is not always possible, but in most cases, it’s the best solution.

In your case (as in most other cases), this means initializing the pointer in the constructor (i.e. as soon as its lifetime starts) and destroy it at the end of its lifetime. Make the variable private and don’t allow direct write access to it to ensure that it will always stay valid.

This is an often used pattern in C++ and it effectively bounds the object lifetime of the pointee to the lifetime of your class. Sometimes, it might also be a viable solution to provide some kind of reset that deletes the pointer and immediately re-initializes it. If this is written in an exception-safe way, you’ve also ensured that your pointer will never be invalid.

Do not create a boolean flag to keep track of your pointer’s validity. This solution has no advantage, and many disadvantages, to setting the pointer to 0.

share|improve this answer

answered Dec 19 ’08 at 18:12

Konrad RudolphKonrad Rudolph

438k109109 gold badges840840 silver badges10801080 bronze badges

add a comment
 | 

4

The whole point of the constructor is that after it has completed all member variables are correctly defined. In this case NULL is a valid initial value.

Calling delete on NULL is well defined.

More normally though you would expect the constructor to define the value of the RAW pointer. Also because your object contains a RAW pointer and obviously owns it (it is deleting it, this implies ownership) you MUST also make sure you override the compiler generated versions of Copy Constructor and Assignment Operator.

class MyClass
{
public:
MyClass()
:pointer(NULL) // valid value.
{}
~MyClass()
{
delete pointer; // This is fine.
}

void initializePointer() // Missing return type
{
pointer = new OtherClass();
}

private:
MyClass(MyClass const& copy); // If you don’t define these
MyClass& operator=(MyClass const& copy);// two the compiler generated ones
// will do nasty things with owned
// RAW pointers.

OtherClass* pointer;
};

Alternatively you can use one of the standard smart pointers. Probably std::auto_ptr<> unless you really want to make the object copyable.

share|improve this answer

answered Dec 19 ’08 at 18:49

Martin YorkMartin York

217k7070 gold badges285285 silver badges505505 bronze badges

add a comment
 | 

2

You should always initialize your pointers to NULL in your constructor; that way you can check in the destructor if it’s been initialized. Also, it’s more efficient to do it in the constructor’s argument list like so:

MyClass::MyClass() : pointer(NULL)
{
}

MyClass::~MyClass()
{
if(pointer != NULL) { delete pointer; }
}

Likewise, you should also set the value to NULL when you delete it and check the value against null when allocating it, if the object is going to be re-initialized many times during the lifespan of your program. However, setting the value to NULL in the destructor won’t make any difference, since the object is obviously going to be destroyed anyways.

The advantage of doing it this way (instead of saying “pointer = NULL;” explicitly in the constructor) is that the compiler is already implicitly doing an assignment like this for you. Doing a manual assignment makes it happen twice, which normally isn’t a big deal except if you are making many instances of your class in a big loop or something.

share|improve this answer

answered Dec 19 ’08 at 18:07

Nik ReimanNik Reiman

33.8k2525 gold badges9696 silver badges155155 bronze badges

Your code is meaningless in C++, since delete already includes a NULL check. Do not check for null manually before deleting!

– Konrad Rudolph
Dec 19 ’08 at 18:14

@Konrad: I wouldn’t call it “meaningless”, but definitely “redundant” and “unnecessary”

– James Curran
Dec 19 ’08 at 18:28

add a comment
 | 

1

You can’t, AFAIK I know. A standard method is to set it to NULL when it contains no valid value. Leaving pointers around that point to invalid memory is bad practice under any circumstances. If you stick to this, you can always check for NULL to see if it’s “defined” or not.

share|improve this answer

answered Dec 19 ’08 at 18:08

Vilx-Vilx-

91.3k7575 gold badges247247 silver badges386386 bronze badges

add a comment
 | 

1

An additional answer that no else has mentioned yet is to use a smart pointer object instead of a raw pointer. Depending on how the pointer is subsequently used, std::auto_ptr, boost::shared_ptr, or a number of other smart pointer classes might be appropriate here. boost::scoped_ptr might also work if you change how initializePointer() works a little bit.

That way the smart pointer takes care of remembering whether it’s valid or not and deleting itself when the containing object is destroyed:

class MyClass {
public:

MyClass();

~MyClass() {
}

initializePointer() {
pointer.reset( new OtherClass());
}

private:

std::auto_ptr<OtherClass> pointer;

};

share|improve this answer

answered Dec 19 ’08 at 18:49

Michael BurrMichael Burr

296k4242 gold badges461461 silver badges695695 bronze badges

add a comment
 | 

1

The real answer is that of litb, but I just wanted to make a side comment. Using smart pointers (in this case std::auto_ptr suffices) takes care of the problem and has the advantage that you will not need to remember to delete the pointer in the destructor. In fact default destructor (generated by the compiler) will take care of memory resources.

Making the comment even more general, you class should declare assignment operator and copy constructor marked as private (and not defined) or manually defined to avoid double deletes of the pointer. Compiler provided operator== and copy constructor will just copy the pointer and eventually you will get into a double delete. I write this here since that is also something to take into account if you use std::auto_ptr with the added strangeness of the copy semantics in auto_ptr.

share|improve this answer

edited May 23 ’17 at 12:13

Community♦

111 silver badge

answered Dec 19 ’08 at 18:47

David Rodríguez – dribeasDavid Rodríguez – dribeas

182k1717 gold badges253253 silver badges452452 bronze badges

add a comment
 | 

Your Answer

Thanks for contributing an answer to Stack Overflow!Please be sure to answer the question. Provide details and share your research!But avoid …Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.To learn more, see our tips on writing great answers.

Draft saved
Draft discarded

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Submit

Post as a guest

Name

Email
Required, but never shown

Post Your Answer

Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged c++ pointers or ask your own question.

Blog

Podcast: Make my Monolith a Micro

When laziness is efficient: Make the most of your command line

Featured on Meta

TLS 1.0 and TLS 1.1 removal for Stack Exchange services

Did Stack Exchange cut the number of negative comments nearly in half between…

An account of my meeting with the Stack Overflow management team

Visit chat

Linked

86

Testing pointers for validity (C/C++)

12

How do you check for an invalid pointer?

1

C++ – Check if pointer is pointing to valid memory (Can’t use NULL checks here)

Related

3181What are the differences between a pointer variable and a reference variable in C++?430What are the differences between struct and class in C++?1774What is a smart pointer and when should I use one?4245The Definitive C++ Book Guide and List8722What is the “–>” operator in C++?2105What are the basic rules and idioms for operator overloading?435How many levels of pointers can we have?1558Why should I use a pointer rather than the object itself?

Hot Network Questions

Using two tires on one wheel to prevent punctures?

Is it legal to photograph and test ATMs?

Recovering from stumbling over words

Quoting GPL licensed text in presentation slides

In the UK parliament, how much of Prime Minister’s Questions is pre-planned?

Count regex matches

Why is the Fourier transform so ubiquitous?

How to write the definition of each term in an equation with pointing arrows?

How Do I Define Smells I Have Never Experienced?

Reversed Iota’s

Using std::vector as view on to raw memory

What documents were needed for a woman to register to vote in UK elections after 1918

Why exactly did telegraphs have to use “STOP” instead of a period and “QUOTE” instead of a quotation mark? (Or special codes.)

Points, Hours, Capacity

What is the Function of Pressurization Light on Exit Doors for Commercial Airliners?

Unix Haters handbook – guaranteeing synchronous,atomic operations

What are the official opposing schools of magic?

What does “D.” stand for?

How to explain that there can only be one magic portal between a planet and another

Corner modelling technique

OpenSSL not producing messages of expected size

Double deck vs wide body airliner, why would anyone build a double deck one?

Multivariate normal distribution transformation

What are these chair-like things in hotels?

more hot questions

Question feed

Subscribe to RSS

Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-cpp

Leave a Reply

Your email address will not be published. Required fields are marked *