473,386 Members | 1,647 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.

Checking pointers

When a function is given a pointer, it is tempting to do an assert on
the pointer to see if it is not NULL. But even if it is not NULL, it
could still be invalid or wrong. What we really want to know is that it
points to memory that we have access to. How about doing this:

void f(int* p)
{
assert(*((char*)p) == *((char*)p);
}

To see if pointer points to something that I have access to?

Is there another way of do something like this?

/David

Nov 15 '05 #1
7 1533
If it is invalid it will still result in exception when we do *p i.e.
trying to access the memory...

Nov 15 '05 #2


pi************@gmail.com wrote:
When a function is given a pointer, it is tempting to do an assert on
the pointer to see if it is not NULL. But even if it is not NULL, it
could still be invalid or wrong. What we really want to know is that it
points to memory that we have access to. How about doing this:

void f(int* p)
{
assert(*((char*)p) == *((char*)p);
}

To see if pointer points to something that I have access to?

Is there another way of do something like this?

/David


If p is not a valid address, accessing it will cause exception.
<OT>
On a unix system, the kernel posts signal SIGSEGV to the application
indication when it accesses any invalid address. So, first insatll
a handler for SIGSEGV. Do a setjmp() before varifying the address
and then do a longjump from the signal handler.
In embedded systems, you may replace the exception handler with that
of yours that would pass some information to the application
whether the address was valid/invalid.
</OT>

Nov 15 '05 #3
pi************@gmail.com wrote:
When a function is given a pointer, it is tempting to do an assert on
the pointer to see if it is not NULL. But even if it is not NULL, it
could still be invalid or wrong. What we really want to know is that it
points to memory that we have access to. How about doing this:

void f(int* p)
{
assert(*((char*)p) == *((char*)p);
The compiler could optimise this away since it is always undefined
behaviour (if p is not a valid pointer) or true.

On systems where the compiler implements the test the most likely
results with an invalid pointer are either a crash (SIGSEGV on *nix) or
it returning true and you continuing with an invalid pointer.
}

To see if pointer points to something that I have access to?

Is there another way of do something like this?


This has been discussed here before. There is absolutely no portable way
to determine if a pointer is valid. If you want to know if it is
possible on a specific implementation then ask on a group dedicated to
that implementation.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 15 '05 #4
pi************@gmail.com wrote:
When a function is given a pointer, it is tempting to do an assert on
the pointer to see if it is not NULL. But even if it is not NULL, it
could still be invalid or wrong. What we really want to know is that it
points to memory that we have access to.
That's not really good enough. What you really want to
know is that the pointer points "where it ought to," which
is much harder to characterize. Using assorted non-portable
tricks you might be able to learn whether a pointer points to
a valid memory location, whether it's correctly aligned for
its type, whether the memory is readable and/or writeable,
and maybe other things, too. If these tests fail you may
conclude that a pointer is incorrect, but if they all pass
you still don't know if the pointer is "right."
How about doing this:

void f(int* p)
{
assert(*((char*)p) == *((char*)p);
}

To see if pointer points to something that I have access to?
If `p' doesn't have a valid pointer value, the attempt
to use it causes undefined behavior. (Another respondent
said "accessing it will cause exception," but he is wrong.
"An exception" is among the things that might happen -- but
it might not, too.) In other words, your test is reliable
only if `p' is valid; if `p' is invalid there is no telling
what might happen.
Is there another way of do something like this?


I can think of nothing portable. And, as I've suggested
above, I think the various non-portable tests you might be
able to make are at best half-measures. (Confession: I have
not personally used things like Purify or valgrind and cannot
speak to their effectiveness -- but certainly a "spot-check"
test unsupported by considerable additional machinery is of
limited effectiveness.)

C programmers find themselves doing a lot of "manual"
memory management. This has its good side (flexibility) and
its bad (susceptibility to error). The kind of test you
propose can detect some kinds of errors, but my impression
is that they are the minority: it's much more common to use
a "stale" pointer by mistake or to make an off-by-one error
and point to the neighbor of the intended object than it is
to pull a completely garbage pointer right out of the blue.
It may sound like a counsel of perfection, but I think the
only way to survive is discipline: you need to construct little
"mini-proofs" of correctness as you go along. It's not infallible
(so few things are), but it seems more effective than trying
to apply an unreliable test after the fact.

--
Eric Sosman
es*****@acm-dot-org.invalid

Nov 15 '05 #5
Eric Sosman wrote:
pi************@gmail.com wrote:
When a function is given a pointer, it is tempting to do an
assert on the pointer to see if it is not NULL. But even if it is
not NULL, it could still be invalid or wrong. What we really want
to know is that it points to memory that we have access to.


That's not really good enough. What you really want to
know is that the pointer points "where it ought to," which
is much harder to characterize. Using assorted non-portable
tricks you might be able to learn whether a pointer points to
a valid memory location, whether it's correctly aligned for
its type, whether the memory is readable and/or writeable,
and maybe other things, too. If these tests fail you may
conclude that a pointer is incorrect, but if they all pass
you still don't know if the pointer is "right."


Such tricks depend on what the pointer is supposed to point to.
For example, in a doubly linked list, one can check that:

(p->next>-prev == p) && (p->prev->next == p)

(with suitable allowances for the ends of the list). My nmalloc
mechanism for DJGPP uses this sort of thing as self protection, and
it reduces the chance of a wild pointer destroying the entire
malloc arena.
--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 15 '05 #6
ju**********@yahoo.co.in writes:
pi************@gmail.com wrote:
When a function is given a pointer, it is tempting to do an assert on
the pointer to see if it is not NULL. But even if it is not NULL, it
could still be invalid or wrong. What we really want to know is that it
points to memory that we have access to. How about doing this:

void f(int* p)
{
assert(*((char*)p) == *((char*)p);
}

To see if pointer points to something that I have access to?

Is there another way of do something like this?

/David


If p is not a valid address, accessing it will cause exception.
<OT>
On a unix system, the kernel posts signal SIGSEGV to the application
indication when it accesses any invalid address. So, first insatll
a handler for SIGSEGV. Do a setjmp() before varifying the address
and then do a longjump from the signal handler.
In embedded systems, you may replace the exception handler with that
of yours that would pass some information to the application
whether the address was valid/invalid.
</OT>


As others have pointed out, there is no portable way to determine
whether a pointer is valid. There are a number of non-portable ways
to do this check (such has catching SIGSEGV) -- but that still leaves
the question of what to do once you've detected the error.

An invalid pointer almost certainly indicates a bug in your program.
Attempting to continue executing with a known bug could well cause
more damage. Very often, the best way to handle the bug is to let the
program die immediately, and let the operating system produce whatever
diagnostics it can. Then fix the bug, recompile, and try again -- or
submit a bug report and ask for your money back.

In some cases, you might want to do some cleanup before terminating
the program. For example, you might try to update and close any open
files to avoid losing too much information. This can still be
dangerous, though, if the bug can affect the cleanup code. It's often
better to write the program so it's always in a consistent state (for
example, any file are periodically updated); this will also handle
things like turning off the power while the program is running.

In some (but not all) safety-critical applications, shutting down the
program might be the worst thing you could do. For example, you might
have a choice between attempting to continue executing (perhaps in
some safe mode) and letting the airplane crash. In such cases, it
makes sense to use whatever system-specific means are available to
detect errors -- and then kick yourself for letting such an error get
into the production version of the program. (Many would question
whether C is an acceptable language for such an application.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 15 '05 #7


Keith Thompson wrote:
ju**********@yahoo.co.in writes:
pi************@gmail.com wrote:
When a function is given a pointer, it is tempting to do an assert on
the pointer to see if it is not NULL. But even if it is not NULL, it
could still be invalid or wrong. What we really want to know is that it
points to memory that we have access to. How about doing this:

void f(int* p)
{
assert(*((char*)p) == *((char*)p);
}

To see if pointer points to something that I have access to?

Is there another way of do something like this?

/David


If p is not a valid address, accessing it will cause exception.
<OT>
On a unix system, the kernel posts signal SIGSEGV to the application
indication when it accesses any invalid address. So, first insatll
a handler for SIGSEGV. Do a setjmp() before varifying the address
and then do a longjump from the signal handler.
In embedded systems, you may replace the exception handler with that
of yours that would pass some information to the application
whether the address was valid/invalid.
</OT>


As others have pointed out, there is no portable way to determine
whether a pointer is valid. There are a number of non-portable ways
to do this check (such has catching SIGSEGV) -- but that still leaves
the question of what to do once you've detected the error.

An invalid pointer almost certainly indicates a bug in your program.
Attempting to continue executing with a known bug could well cause
more damage. Very often, the best way to handle the bug is to let the
program die immediately, and let the operating system produce whatever
diagnostics it can. Then fix the bug, recompile, and try again -- or
submit a bug report and ask for your money back.


In embedded domain, sometimes it becomes necessary to check for the
validity of addressses. For eg, Suppose the user wants to set a
breakpoint at some address (the address being entered as an input by
the user) then it is necessary to validate that address because it
may be possible that user has given some invalid address.
Similarly, while taking memory dumps, the user address must be
validated.
But all this is platform specific.

Nov 15 '05 #8

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

Similar topics

30
by: Michael B Allen | last post by:
I have a general purpose library that has a lot of checks for bad input parameters like: void * linkedlist_get(struct linkedlist *l, unsigned int idx) { if (l == NULL) { errno = EINVAL;...
14
by: sathya_me | last post by:
Dear clc, I have a variable void *a; Since variable "a" can be assigned (point to) any type and also any type can be assigned to "a" (i.e means "a" = any typed variable; any typed variable =...
99
by: Mikhail Teterin | last post by:
Hello! Consider the following simple accessor function: typedef struct { int i; char name; } MY_TYPE; const char *
20
by: Xiaoshen Li | last post by:
Hi, I am reading the book "Concepts of programming languages" by R. W. Sebesta. He said: "One of the most important reasons why C is both liked and disliked is its lack of complete type...
351
by: CBFalconer | last post by:
We often find hidden, and totally unnecessary, assumptions being made in code. The following leans heavily on one particular example, which happens to be in C. However similar things can (and...
7
by: copx | last post by:
How do you implement an event queue in C? The problem I had is that events needed pointers to the objects they affect and I do not know any way to check if pointers are actually valid in C. The...
4
by: Mike C# | last post by:
Is there a better way than IsBadReadPtr() to check for a bad pointer? Thanx
51
by: atv | last post by:
Hi, Just to check, if i set a pointer explicitly to NULL, i'm not allowed to dereference it? Why is that, it's not like it's pointing to any garbage right? Why else set it to NULL. I can remember...
125
by: jacob navia | last post by:
We hear very often in this discussion group that bounds checking, or safety tests are too expensive to be used in C. Several researchers of UCSD have published an interesting paper about this...
27
by: Aaron Hsu | last post by:
Hey all, After seeing the Secure version I/O functions thread, it occured to me that maybe not everyone agrees with the almost universal adage that I have heard. I have Always been told that...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.