473,386 Members | 1,668 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Array of pointers. How to check index without failure?

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.

Aug 2 '07 #1
15 2554
Lorn wrote:
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 ...
}
Aug 2 '07 #2
Lorn <ef*******@yahoo.comwrote:
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.
Aug 2 '07 #3


Daniel T. wrote:
Lorn <ef*******@yahoo.comwrote:
>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.
Aug 3 '07 #4
I V
On Thu, 02 Aug 2007 17:21:42 -0700, Vaibhav Nivargi wrote:
Daniel T. wrote:
>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.
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.
Aug 3 '07 #5
On Aug 2, 8:41 pm, I V <ivle...@gmail.comwrote:
On Thu, 02 Aug 2007 17:21:42 -0700, Vaibhav Nivargi wrote:
Daniel T. wrote:
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.

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

Aug 3 '07 #6
I V
On Fri, 03 Aug 2007 03:38:10 +0000, Jeff wrote:
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.
Aug 3 '07 #7
On Aug 3, 5:38 am, Jeff <jeff.griff...@gmail.comwrote:
On Aug 2, 8:41 pm, I V <ivle...@gmail.comwrote:
On Thu, 02 Aug 2007 17:21:42 -0700, Vaibhav Nivargi wrote:
Daniel T. wrote:
>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.
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.
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).

--
James Kanze (GABI Software) email:ja*********@gmail.com
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

Aug 3 '07 #8
On Aug 3, 4:53 am, James Kanze <james.ka...@gmail.comwrote:
On Aug 3, 5:38 am, Jeff <jeff.griff...@gmail.comwrote:
On Aug 2, 8:41 pm, I V <ivle...@gmail.comwrote:
On Thu, 02 Aug 2007 17:21:42 -0700, Vaibhav Nivargi wrote:
Daniel T. wrote:
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.
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.

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).

--
James Kanze (GABI Software) email:james.ka...@gmail.com
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

Aug 3 '07 #9
James Kanze wrote:
....
>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.
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).


Aug 3 '07 #10
Gianni Mariani <gi*******@mariani.wswrote in news:46b3a088$0$31411
$5*******@per-qv1-newsreader-01.iinet.net.au:
James Kanze wrote:
...
>>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.

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.
Aug 3 '07 #11
On 2007-08-03 19:11:30 -0400, Andre Kostur <nn******@kostur.netsaid:
Gianni Mariani <gi*******@mariani.wswrote in news:46b3a088$0$31411
$5*******@per-qv1-newsreader-01.iinet.net.au:
>James Kanze wrote:
...
>>>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.

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.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Aug 3 '07 #12
On Aug 3, 4:41 pm, Pete Becker <p...@versatilecoding.comwrote:
[message redacted]

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

Aug 3 '07 #13
Andre Kostur wrote:
Gianni Mariani <gi*******@mariani.wswrote in news:46b3a088$0$31411
$5*******@per-qv1-newsreader-01.iinet.net.au:
>James Kanze wrote:
...
>>>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.
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.
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.
Aug 4 '07 #14
On Aug 4, 2:47 am, Gianni Mariani <gi3nos...@mariani.wswrote:
"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.

--
James Kanze (GABI Software) email:james.kanze:gmail.com
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
Aug 4 '07 #15
James Kanze wrote:
On Aug 4, 2:47 am, Gianni Mariani <gi3nos...@mariani.wswrote:
>"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.
"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
Aug 5 '07 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Nicolas Pernetty | last post by:
Hello, I'm trying to find a clear and fast equivalent to the index method of plain python list : >> a = >> a.index(4) 2 I have to use it on a Numeric array, so the best I've come up with...
7
by: _ed_ | last post by:
I'd like to build a class or struct composed of pointers to variables. Does this require dropping into an 'unsafe' block, or is there a trick? .... int value1 = 1234; bool value2 = false;...
7
by: John | last post by:
Hi Is there a way to create an array of strings of subscript of type index too? Like; x("Element A")="Value for element A" Thanks Regards
7
by: cdg | last post by:
Would anyone explain how to return an array that wasn`t passed from "main" using a pointer. I'm not understanding how scope and memory are involved in this. However, I do know that there are two...
27
by: lovecreatesbea... | last post by:
This code snippet is an exercise on allocating two dimension array dynamically. Though this one is trivial, is it a correct one? Furthermore, when I tried to make these changes to the original...
11
by: Piotrek | last post by:
Hi, I have no idea why my reallocation function (myadd) is breaking up my array. I'm trying to solve it and it took me few hours already. Maybe you can look at my code and explain me what is...
3
by: Robert Bevington | last post by:
Hi all, I ran into memory problems while tying to search and replace a very large text file. To solve this I break the file up into chunks and run the search and replace on each chunk. This...
1
by: alansharp | last post by:
Hi guys Im attempting to write conways Game of life and need to use a pointer and 2 arrays. The reason im using a pointer is hopefully to speed up the code rather than copying the array >...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.