Array of pointers. How to check index without failure?

L

Lorn

Hello, I have a static array of pointers to custom objects: MyObject *
aMyObjects[500]

How can i can check if an index has a pointer stored? Assuming without
checking leads to crashes if no pointer is there: aMyObjects[0]-
stuff... crash.

Any help with this would be much appreciated.
 
G

Gianni Mariani

Lorn said:
Hello, I have a static array of pointers to custom objects: MyObject *
aMyObjects[500]

How can i can check if an index has a pointer stored? Assuming without
checking leads to crashes if no pointer is there: aMyObjects[0]-
stuff... crash.

Any help with this would be much appreciated.


If the value of the pointer is null (0) then it's not pointing to
anything. Note that you need to initialize your array so that those
elements not pointing to somthing are set to null.

T * x = 0;
....
if ( x )
{
x->stuff ...
}
 
D

Daniel T.

Lorn said:
Hello, I have a static array of pointers to custom objects: MyObject *
aMyObjects[500]

How can i can check if an index has a pointer stored? Assuming without
checking leads to crashes if no pointer is there: aMyObjects[0]-
stuff... crash.

Any help with this would be much appreciated.

Set the values to 0 or NULL. Check to see if the value is 0 before
dereferencing it.
 
V

Vaibhav Nivargi

Daniel said:
Lorn said:
Hello, I have a static array of pointers to custom objects: MyObject *
aMyObjects[500]

How can i can check if an index has a pointer stored? Assuming without
checking leads to crashes if no pointer is there: aMyObjects[0]-
stuff... crash.
Any help with this would be much appreciated.

Set the values to 0 or NULL. Check to see if the value is 0 before
dereferencing it.

To protect against dangling pointers, a better approach would be to use
an extra 'initialized' bit for each pointer set to 1/0 appropriately.
 
I

I V

To protect against dangling pointers, a better approach would be to use
an extra 'initialized' bit for each pointer set to 1/0 appropriately.

How would that help? You'ld have to manually set/clear the initialized bit
whenever the status changed, and I would have thought that's no easier or
harder than setting the pointer to 0.
 
J

Jeff

How would that help? You'ld have to manually set/clear the initialized bit
whenever the status changed, and I would have thought that's no easier or
harder than setting the pointer to 0.

Be careful using the "if(p)" syntax; it does an integer comparison on
the pointer
which isn't valid on all platforms. Most compilers have an option to
prefill
any static memory block to zeros; use it if it is available and then
use
"if( ((X*)p) != ((X*)0))". It's a little harder for you to write, but
it
guarantees a valid comparision.

One other option that IBM used in it's version of the Xerces library
was to
surround all object references with a "try-catch" block and then they
surpress
the exception when they hit an invalid pointer. This works, but it's a
real performance
hog. An XML parser that I had to maintain (without being allowed to
change it) spent
nearly 50% of its runtime in these exception handlers.

Jeff Griffith
 
A

Alf P. Steinbach

* Jeff:
Be careful using the "if(p)" syntax; it does an integer comparison on
the pointer
which isn't valid on all platforms.

Sorry, that is doubly incorrect.

First, in C++, and C, "if(p)" is perfectly valid on all platforms,
provided "p" doesn't have an indeterminate value. Second, how p is
checked for nullpointer'ness depends on the implementation. Since all
machine code operations at a sufficient low level are integer operations
you might say it's an integer comparision, but that's meaningless.

To be more clear you can compare directly against a nullpointer,
"if(p!=0)", or use a double negation, "if(!!p)". But the latter is only
more clear to good experienced programmers, in general not to the
average programmer or novice, and so is perhaps best avoided. By the
way, note that "if(p!=0)" is not an integer comparision.
 
I

I V

One other option that IBM used in it's version of the Xerces library
was to
surround all object references with a "try-catch" block and then they
surpress
the exception when they hit an invalid pointer. This works, but it's a
real performance
hog. An XML parser that I had to maintain (without being allowed to
change it) spent
nearly 50% of its runtime in these exception handlers.

Are you sure you're not thinking of the Java version of Xerces? Accessing
an invalid pointer in C++ doesn't generally cause an exception.
 
J

James Kanze

Be careful using the "if(p)" syntax; it does an integer
comparison on the pointer which isn't valid on all platforms.

No it doesn't. The condition in an if must have type bool.
There is an implicit conversion of pointer to bool, which is
basically the equivalent of "p != NULL". Code like "if (p)" may
be unreadable, and it's not the sort of thing you'd ever see in
well written C++, but it is perfectly legal and well defined.
Most compilers have an option to prefill any static memory
block to zeros;

I've never heard of a compiler with such an *option*. The
language standard requires that all objects with static storage
duration be "zero initialize" before the program starts. "Zero
initialized" means, basically, that each low level type is
initialized as if 0 were assigned to it. Again, there is a
special conversion, so that the integer value 0 converts to a
null pointer; even if null pointers aren't all bits 0, a pointer
with static storage duration is guaranteed to be initialized
with a null pointer value. (The one exception is in a union.
Only the first element of a union is zero initialized.)
use it if it is available and then
use
"if( ((X*)p) != ((X*)0))". It's a little harder for you to write, but
it
guarantees a valid comparision.

You don't have to get carried away:
if ( p == NULL )
or
if ( p == 0 )
work perfectly well, and are perfectly readable.
One other option that IBM used in it's version of the Xerces
library was to surround all object references with a
"try-catch" block and then they surpress the exception when
they hit an invalid pointer. This works, but it's a real
performance hog. An XML parser that I had to maintain (without
being allowed to change it) spent nearly 50% of its runtime in
these exception handlers.

I doubt that it was written in C++. In C++, dereferencing a
null pointer results in undefined behavior; on typical desktop
machines, it will cause a fatal program crash (core dump, in
Unix-speak).

Of course, since the behavior is undefined, an implementation is
free to do whatever it wants, including raise an exception.
IMHO, that would not be very good from a QoI point of view, but
it would certainly be conforming (as would be formatting your
hard disk).
 
L

Lorn

No it doesn't. The condition in an if must have type bool.
There is an implicit conversion of pointer to bool, which is
basically the equivalent of "p != NULL". Code like "if (p)" may
be unreadable, and it's not the sort of thing you'd ever see in
well written C++, but it is perfectly legal and well defined.


I've never heard of a compiler with such an *option*. The
language standard requires that all objects with static storage
duration be "zero initialize" before the program starts. "Zero
initialized" means, basically, that each low level type is
initialized as if 0 were assigned to it. Again, there is a
special conversion, so that the integer value 0 converts to a
null pointer; even if null pointers aren't all bits 0, a pointer
with static storage duration is guaranteed to be initialized
with a null pointer value. (The one exception is in a union.
Only the first element of a union is zero initialized.)


You don't have to get carried away:
if ( p == NULL )
or
if ( p == 0 )
work perfectly well, and are perfectly readable.


I doubt that it was written in C++. In C++, dereferencing a
null pointer results in undefined behavior; on typical desktop
machines, it will cause a fatal program crash (core dump, in
Unix-speak).

Of course, since the behavior is undefined, an implementation is
free to do whatever it wants, including raise an exception.
IMHO, that would not be very good from a QoI point of view, but
it would certainly be conforming (as would be formatting your
hard disk).

--
James Kanze (GABI Software) email:[email protected]
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Great replies guys. Thanks a lot for your help and insights.

I had initialized the array to NULL or zero previously, but had some
problems with that implementation. Will revisit though as that seems
to be the overall theme of the advice.

With much apprecitation,
Lorn
 
G

Gianni Mariani

James Kanze wrote:
....
No it doesn't. The condition in an if must have type bool.
There is an implicit conversion of pointer to bool, which is
basically the equivalent of "p != NULL". Code like "if (p)" may
be unreadable, and it's not the sort of thing you'd ever see in
well written C++, but it is perfectly legal and well defined.

if (p) *IS* readable. There is nothing ambiguous, unclear or not "well
written" about it other than it's missing one of the silliest standard
macros since the beginning C compared to if (p != NULL).
 
A

Andre Kostur

James Kanze wrote:
...

if (p) *IS* readable. There is nothing ambiguous, unclear or not "well
written" about it other than it's missing one of the silliest standard
macros since the beginning C compared to if (p != NULL).

I disagree. I prefer the explicit test against NULL. (I'd prefer it even
more if they standardize on a keyword nulptr). I dislike testing implicit
conversions to bool, so the only time I write "if (p)" is only if p is a
bool. If it is anything else, I'll write out the full test; "if (p != 0)"
for example.
 
P

Pete Becker

I disagree. I prefer the explicit test against NULL. (I'd prefer it even
more if they standardize on a keyword nulptr). I dislike testing implicit
conversions to bool, so the only time I write "if (p)" is only if p is a
bool. If it is anything else, I'll write out the full test; "if (p != 0)"
for example.
 
R

redfloyd

[message redacted]

Pete, I think you forgot to write something. It was just the quoted
text, with no addition! :)
 
G

Gianni Mariani

Andre said:
I disagree. I prefer the explicit test against NULL. (I'd prefer it even
more if they standardize on a keyword nulptr). I dislike testing implicit
conversions to bool, so the only time I write "if (p)" is only if p is a
bool. If it is anything else, I'll write out the full test; "if (p != 0)"
for example.

Listen ! My religion is better than yours so there...

"if ( thing )" has been part of C and C++ and Perl and a number of
languages. It's clearly defined what it does. There is no reason to
have to specify it any more clearly. The "!= NULL" is just noise.

It clearly conforms to the path of least surprise rule.
 
J

James Kanze

"if ( thing )" has been part of C and C++ and Perl and a number of
languages.

That doesn't make it good engineering. Say what you mean, and
mean what you say. Every good company I've seen or heard about
has an absolute rule that requires the explicit test, no
exceptions allowed.
 
G

Gianni Mariani

James said:
That doesn't make it good engineering. Say what you mean, and
mean what you say. Every good company I've seen or heard about
has an absolute rule that requires the explicit test, no
exceptions allowed.

"Every good company I've seen or heard about" ?

I have never seen any bugs ever related to "if (p)", however I have seen
many bugs related to "if (p != NULL)".

Sounds like a really silly rule to me.

G
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,289
Messages
2,571,448
Members
48,126
Latest member
ToneyChun2

Latest Threads

Top