# Test if pointer points to allocated memory

Discussion in 'C Programming' started by Andrew, Jan 21, 2004.

1. ### AndrewGuest

Is there anyway to test if a pointer points to allocated memory or
not?
For example if I have a pointer such as char *p is there a standard
way to test whether an assignment such as the following has been
applied?
p = (char *) malloc(sizeof(char) * n);

Andrew, Jan 21, 2004

2. ### Joona I PalasteGuest

Andrew <> scribbled the following:
> Is there anyway to test if a pointer points to allocated memory or
> not?
> For example if I have a pointer such as char *p is there a standard
> way to test whether an assignment such as the following has been
> applied?
> p = (char *) malloc(sizeof(char) * n);

Not portably.

--
/-- Joona Palaste () ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"Outside of a dog, a book is a man's best friend. Inside a dog, it's too dark
- Groucho Marx

Joona I Palaste, Jan 21, 2004

3. ### peteGuest

Andrew wrote:
>
> Is there anyway to test if a pointer points to allocated memory or
> not?
> For example if I have a pointer such as char *p is there a standard
> way to test whether an assignment such as the following has been
> applied?
> p = (char *) malloc(sizeof(char) * n);

If a pointer is uninitialized or has been freed
without being reassigned, then you can't evaluate the pointer.

If you know that a pointer value is either NULL or
points to memory, you can check for NULL.

I think you could just add another object to keep
track of if that line was executed.

int applied = 0;

p = (char *) malloc(sizeof(char) * n);
applied = 1;

I also suspect that you have a question about the
return value of malloc, but I'm not sure.

After a malloc assignment has been made,
you always need to check for NULL.

p = malloc(n * sizeof *p);
if (p == NULL) {
/* deal with it intelligently */
}

--
pete

pete, Jan 21, 2004
4. ### Dan PopGuest

In <> (Andrew) writes:

>Is there anyway to test if a pointer points to allocated memory or
>not?
>For example if I have a pointer such as char *p is there a standard
>way to test whether an assignment such as the following has been
>applied?
>p = (char *) malloc(sizeof(char) * n);

If the pointer has not yet been initialised or if it points to memory
that has been already freed, you're not even allowed to evaluate it in
a portable C program.

In a well designed program, you don't need such a check: you should
know whether it is initialised or not. The alternative takes a lot of
programming discipline: initialise each pointer with NULL at the point of
definition and reset it to NULL as soon as the object it used to point to
no longer exists (or is about to disappear). You may find the
following macro useful for this purpose:

#define FREE(p) (free(p), p = NULL)

but it is far from solving the problem, because there may be other
pointers pointing into the block being free'd. But malloc and friends
are not the full story. Consider:

char *global;

void foo(void)
{
char buff[100];
global = buff;
...
}

You need a "global = NULL;" before returning from foo(), because the life
of buff ends at that point.

So, if you're *extremely* careful, you can always use p != NULL to tell
whether p is pointing to some object or not (bugs caused by omitting to
reset a pointer can be very difficult to track). IMHO, it's much easier
to avoid the need of such checks in the first place.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email:

Dan Pop, Jan 21, 2004
5. ### CBFalconerGuest

Andrew wrote:
>
> Is there anyway to test if a pointer points to allocated memory or
> not?
> For example if I have a pointer such as char *p is there a standard
> way to test whether an assignment such as the following has been
> applied?
> p = (char *) malloc(sizeof(char) * n);

Don't cast malloc. It is unnecessary and hides errors.

execute "free(p);" and the program goes BOOM you can be fairly
sure that p was not malloced, or has already been freed. I'm sure
this is a great help and comfort to you.

--
Chuck F () ()
Available for consulting/temporary embedded and systems.

CBFalconer, Jan 21, 2004
6. ### Fred L. KleinschmidtGuest

Andrew wrote:
>
> Is there anyway to test if a pointer points to allocated memory or
> not?
> For example if I have a pointer such as char *p is there a standard
> way to test whether an assignment such as the following has been
> applied?
> p = (char *) malloc(sizeof(char) * n);

Other answers to this post address the pointer being set to malloc'd
memory.
But even if you are very careful to initialize all pointers to NULL, and
re-set them to NULL when you free allocated memory, you can never be
sure a non-NULL pointer points to allocated memory - it may point to
some static or heap string:

static char hello[] = "Hello";
char *p = NULL;
....
p = hello;

If you later test p for non-NULL in order to determine whether to free
it, you will be in big trouble.
--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Common User Interface Services
M/S 2R-94 (206)544-5225

Fred L. Kleinschmidt, Jan 21, 2004
7. ### Sean KenwrickGuest

"Andrew" <> wrote in message
news:...
> Is there anyway to test if a pointer points to allocated memory or
> not?
> For example if I have a pointer such as char *p is there a standard
> way to test whether an assignment such as the following has been
> applied?
> p = (char *) malloc(sizeof(char) * n);

You could try realloc(char * ptr,size) to try and reallocate the memory the
pointer is referencing. Although it is not clear whether realloc() will fail
gracefully (E.g. by returning NULL) or whether it will crash your
application if it is not a valid pointer - I suppose this depends on the
implementation. Its a long shot but its your only hope....

Sean

Sean Kenwrick, Jan 21, 2004
8. ### CBFalconerGuest

Sean Kenwrick wrote:
> "Andrew" <> wrote in message
>
> > Is there anyway to test if a pointer points to allocated memory
> > or not? For example if I have a pointer such as char *p is there
> > a standard way to test whether an assignment such as the
> > following has been applied?
> >
> > p = (char *) malloc(sizeof(char) * n);

>
> You could try realloc(char * ptr,size) to try and reallocate the
> memory the pointer is referencing. Although it is not clear whether
> realloc() will fail gracefully (E.g. by returning NULL) or ..snip..

It is clearly undefined behaviour leading to frisky nasal demons.

--
Chuck F () ()
Available for consulting/temporary embedded and systems.

CBFalconer, Jan 22, 2004
9. ### E. Robert TisdaleGuest

Andrew wrote:

> Is there anyway to test
> if a pointer points to allocated memory or not?
> For example, if I have a pointer such as char *p
> is there a standard way to test whether an assignment
> such as the following has been applied?

> char* p = (char*)malloc(sizeof(char)*n);

if (p > (char*)(&p)) {
// p probably points to a character in automatic storage
// (the program stack)
}
else {
// p probably points to static data or free storage
}

But, of course, the ANSI/ISO C standards do *not* specify this.

E. Robert Tisdale, Jan 22, 2004
10. ### Jack KleinGuest

On Wed, 21 Jan 2004 19:17:17 -0800, "E. Robert Tisdale"
<> wrote in comp.lang.c:

> Andrew wrote:
>
> > Is there anyway to test
> > if a pointer points to allocated memory or not?
> > For example, if I have a pointer such as char *p
> > is there a standard way to test whether an assignment
> > such as the following has been applied?

>
> > char* p = (char*)malloc(sizeof(char)*n);

>
> if (p > (char*)(&p)) {

Undefined behavior. p and &p are not pointers to the same object or
one past the same object or array.

> // p probably points to a character in automatic storage
> // (the program stack)

Not all processors have a stack. Even for those that do, you are
making the unwarranted and unproven assumption that "the stack"
resides at higher memory addresses than other areas. I know of
several architectures where processor hardware requires that the stack
be in low memory.

> }
> else {
> // p probably points to static data or free storage
> }

Or is uninitialized. Or null. Or points to allocated memory that has
been free.

> But, of course, the ANSI/ISO C standards do *not* specify this.

Neither does anyone with any sense, you included.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~ajo/docs/FAQ-acllc.html

Jack Klein, Jan 22, 2004
11. ### E. Robert TisdaleGuest

Jack Klein wrote:

> E. Robert Tisdale wrote:
>
> Undefined behavior.
> p and &p are not pointers to the same object
> or one past the same object or array.

Please elaborate. Why does that make a difference?

>
>
>> // p probably points to a character in automatic storage
>> // (the program stack)

>
> Not all processors have a stack.

But they all have "automatic storage".
The typical implementation of automatic storage is on the program stack.

> Even for those that do, you are
> you are making the unwarranted and unproven assumption that
> "the stack" resides at higher memory addresses than other areas.
> I know of several architectures
> where processor hardware requires that the stack be in low memory.

Name one.

>> }
>> else {
>> // p probably points to static data or free storage
>> }

>
> Or is uninitialized. Or null.
> Or points to allocated memory that has been free.
>
>>But, of course, the ANSI/ISO C standards do *not* specify this.

>
> Neither does anyone with any sense, you included.

I don't know whether I have any sense or not.
But my assertion is easily tested:

> cat main.c

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {
//char c;
//char* p = &c;
char* p = (char*)malloc(sizeof(char));
if (p > (char*)(&p)) {
fprintf(stdout, "p probably points to a character "
"in automatic storage.\n");
}
else {
fprintf(stdout, "p probably points to static data "
"or free storage.\n");
}
return 0;
}

E. Robert Tisdale, Jan 22, 2004
12. ### Jack KleinGuest

On Wed, 21 Jan 2004 21:27:17 -0800, "E. Robert Tisdale"
<> wrote in comp.lang.c:

> Jack Klein wrote:
>
> > E. Robert Tisdale wrote:
> >
> > Undefined behavior.
> > p and &p are not pointers to the same object
> > or one past the same object or array.

>
> Please elaborate. Why does that make a difference?

Paragraph 5 of ISO 9899:1999 section 6.5.8 "Relational operators", a
little thing that defines the standard C language:

<quote>
When two pointers are compared, the result depends on the relative
locations in the address space of the objects pointed to. If two
pointers to object or incomplete types both point to the same object,
or both point one past the last element of the same array object,
they compare equal. If the objects pointed to are members of the same
aggregate object, pointers to structure members declared later compare
greater than pointers to members declared earlier in the structure,
and pointers to array elements with larger subscript values compare
greater than pointers to elements of the same array with lower
subscript values. All pointers to members of the same union object
compare equal. If the expression P points to an element of an array
object and the expression Q points to the last element of the same
array object, the pointer expression Q+1 compares greater than
P. In all other cases, the behavior is undefined.
</quote>

> >> // p probably points to a character in automatic storage
> >> // (the program stack)

> >
> > Not all processors have a stack.

>
> But they all have "automatic storage".
> The typical implementation of automatic storage is on the program stack.
>
> > Even for those that do, you are
> > you are making the unwarranted and unproven assumption that
> > "the stack" resides at higher memory addresses than other areas.
> > I know of several architectures
> > where processor hardware requires that the stack be in low memory.

>
> Name one.

All 8051 processors, limited to lowest 256 8-bit bytes.

All Philips XA processors, limited to lowest 64K 8-bit bytes.

All Texas Instruments TMS320C28xx DSPs, limited to lowest 64K 16-bit
bytes.

Once you leave the common desktop behind, there are quite a few
hardware architectures that limit their hardware stack to specific
regions of memory for a variety of reasons.

> >> }
> >> else {
> >> // p probably points to static data or free storage
> >> }

> >
> > Or is uninitialized. Or null.
> > Or points to allocated memory that has been free.
> >
> >>But, of course, the ANSI/ISO C standards do *not* specify this.

> >
> > Neither does anyone with any sense, you included.

>
> I don't know whether I have any sense or not.
> But my assertion is easily tested:

All that proves is that the one implementation you know, from which
you probably formed the erroneous impression, works the way it works.
This says nothing at all about any other platform/implementation, or
what the language defines.

>
> > cat main.c

> #include <stdio.h>
> #include <stdlib.h>
>
> int main(int argc, char* argv[]) {
> //char c;
> //char* p = &c;
> char* p = (char*)malloc(sizeof(char));
> if (p > (char*)(&p)) {
> fprintf(stdout, "p probably points to a character "
> "in automatic storage.\n");
> }
> else {
> fprintf(stdout, "p probably points to static data "
> "or free storage.\n");
> }
> return 0;
> }
>

Actually it doesn't even prove that, since you neglected to show the
output of the program.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~ajo/docs/FAQ-acllc.html

Jack Klein, Jan 22, 2004
13. ### Richard HeathfieldGuest

E. Robert Tisdale wrote:

> Jack Klein wrote:
>
>> E. Robert Tisdale wrote:
>>
>> Undefined behavior.
>> p and &p are not pointers to the same object
>> or one past the same object or array.

>
> Please elaborate. Why does that make a difference?

Because the Standard defines the comparison of pointers very carefully, in
6.5.8, as follows:

5 When two pointers are compared, the result depends on the
relative locations in the address space of the objects
pointed to. If two pointers to object or incomplete types
both point to the same object, or both point one past the
last element of the same array object, they compare equal.
If the objects pointed to are members of the same aggregate
object, pointers to structure members declared later
compare greater than pointers to members declared earlier
in the structure, and pointers to array elements with
larger subscript values compare greater than pointers to
elements of the same array with lower subscript values. All
pointers to members of the same union object compare equal.
If the expression P points to an element of an array object
and the expression Q points to the last element of the same
array object, the pointer expression Q+1 compares greater
than P. In all other cases, the behavior is undefined.

<snip>

> But my assertion is easily tested:
>
> > cat main.c

> #include <stdio.h>
> #include <stdlib.h>
>
> int main(int argc, char* argv[]) {
> //char c;
> //char* p = &c;
> char* p = (char*)malloc(sizeof(char));

sizeof(char) is guaranteed to be 1. The cast is unnecessary.

> if (p > (char*)(&p)) {

At this point, the program invokes undefined behaviour, and thus its output
cannot be trusted.

--
Richard Heathfield :
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton

Richard Heathfield, Jan 22, 2004
14. ### rahul devGuest

"E. Robert Tisdale" <> wrote in message news:<>...
> Andrew wrote:
>
> > Is there anyway to test
> > if a pointer points to allocated memory or not?
> > For example, if I have a pointer such as char *p
> > is there a standard way to test whether an assignment
> > such as the following has been applied?

>
> > char* p = (char*)malloc(sizeof(char)*n);

>
> if (p > (char*)(&p)) {
> // p probably points to a character in automatic storage
> // (the program stack)
> }
> else {
> // p probably points to static data or free storage
> }
>
> But, of course, the ANSI/ISO C standards do *not* specify this.

malloc() library function uses brk() and sbrk() to increase the
address space of a process. sbrk() is a system call that ask
the kernel to allocate space at the end of "data segment" of
the process. So, the address returned by malloc() should always
be greater than the end of data segment.
Now, the end of data segment may be found by printing the address
of the symbol "end" or the address of the symbol "_end". These
symbols are defined with the appropriate values by the linker.
Or you may use "objdump" to find out the addresses of data segments

-rd

rahul dev, Jan 22, 2004
15. ### Christian BauGuest

In article <>,
"E. Robert Tisdale" <> wrote:

> Jack Klein wrote:
>
> > E. Robert Tisdale wrote:
> >
> > Undefined behavior.
> > p and &p are not pointers to the same object
> > or one past the same object or array.

>
> Please elaborate. Why does that make a difference?

Because the C Standard says it is undefined behavior.

Christian Bau, Jan 22, 2004
16. ### Christian BauGuest

In article <>,
(rahul dev) wrote:

> malloc() library function uses brk() and sbrk() to increase the
> address space of a process.

Does it? I always thought it called NewPtr (). Oh, I see, you are
talking about completely system dependent behavior that only a complete
idiot would rely on in portable code...

> sbrk() is a system call that ask
> the kernel to allocate space at the end of "data segment" of
> the process.

Since I use a machine that doesn't have sbrk(), or a kernel, or a data
segment, of use could that information be?

> So, the address returned by malloc() should always
> be greater than the end of data segment.
> Now, the end of data segment may be found by printing the address
> of the symbol "end" or the address of the symbol "_end". These
> symbols are defined with the appropriate values by the linker.
> Or you may use "objdump" to find out the addresses of data segments
>
> -rd

Christian Bau, Jan 22, 2004
17. ### Jared DykstraGuest

CBFalconer <> wrote in message news:<>...
> Andrew wrote:
> >
> > Is there anyway to test if a pointer points to allocated memory or
> > not?
> > For example if I have a pointer such as char *p is there a standard
> > way to test whether an assignment such as the following has been
> > applied?
> > p = (char *) malloc(sizeof(char) * n);

>
> Don't cast malloc. It is unnecessary and hides errors.
>
> To all practical purposes, your answer is no. However if you
> execute "free(p);" and the program goes BOOM you can be fairly
> sure that p was not malloced, or has already been freed. I'm sure
> this is a great help and comfort to you.

Often free()ing an invalid pointer will not cause a runtime error
immediately. Most of the time you will not encounter an error until
the following malloc()

CBFalconer's solution undefined and dangerous territory in which to

---
Jared Dykstra
http://www.bork.org/~jared

Jared Dykstra, Jan 22, 2004
18. ### Joona I PalasteGuest

Christian Bau <> scribbled the following:
> In article <>,
> (rahul dev) wrote:
>> malloc() library function uses brk() and sbrk() to increase the
>> address space of a process.

> Does it? I always thought it called NewPtr (). Oh, I see, you are
> talking about completely system dependent behavior that only a complete
> idiot would rely on in portable code...

>> sbrk() is a system call that ask
>> the kernel to allocate space at the end of "data segment" of
>> the process.

> Since I use a machine that doesn't have sbrk(), or a kernel, or a data
> segment, of use could that information be?

Interesting, what sort of computer are you using that doesn't have a
kernel?

--
/-- Joona Palaste () ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"You could take his life and..."
- Mirja Tolsa

Joona I Palaste, Jan 22, 2004
19. ### Richard BosGuest

(rahul dev) wrote:

> > Andrew wrote:
> >
> > > Is there anyway to test
> > > if a pointer points to allocated memory or not?

No. That is, a null pointer is guaranteed not to point to any object;
but if a pointer is non-null, there's no way of finding out whether it
is valid, or if so, what kind of memory it points at.

> malloc() library function uses brk() and sbrk() to increase the
> address space of a process.

You don't know that. Maybe on your system they do; all the ISO C
Standard requires is that malloc() attempts to get some memory for the
caller, by whatever means the implementor's author thought best.

Richard

Richard Bos, Jan 22, 2004
20. ### August DerlethGuest

Joona I Palaste wrote:

> Christian Bau <> scribbled the following:
>
>>In article <>,
>> (rahul dev) wrote:
>>
>>>malloc() library function uses brk() and sbrk() to increase the

>
>
>>Does it? I always thought it called NewPtr (). Oh, I see, you are
>>talking about completely system dependent behavior that only a complete
>>idiot would rely on in portable code...

>
>
>>>sbrk() is a system call that ask
>>>the kernel to allocate space at the end of "data segment" of
>>>the process.

>
>
>>Since I use a machine that doesn't have sbrk(), or a kernel, or a data
>>segment, of use could that information be?

>
>
> Interesting, what sort of computer are you using that doesn't have a
> kernel?
>

Could be running an embedded system, where libc handles things right
down to the bare metal.

Could be running PC-DOS, where the `kernel' is simply a program loader
and an interrupt handler. (Calling something so simple a kernel now
would get one laughed out of the industry. )

Could be running an exokernel system, where the process can request
specific addresses in RAM from an extremely minimal resource-protection
procedure that is loosely called a kernel. Comparing an exokernel system
to a monolithic kernel or even a microkernel is an exercise in
stretching definitions, perhaps beyond their breaking point.

The point being, as I'm sure you know, that odd systems exist
/everywhere/ and that Standard C is a good way to handle the complexity
(mainly because it allows us to forget about such things).

--
My address is yvoregnevna gjragl-guerr gjb-gubhfnaq guerr ng lnubb qbg pbz
Note: Rot13 and convert spelled-out numbers to numerical equivalents.

August Derleth, Jan 22, 2004