Test if pointer points to allocated memory

A

Andrew

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);
 
J

Joona I Palaste

Andrew said:
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 ([email protected]) ------------- 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
to read anyway."
- Groucho Marx
 
P

pete

Andrew said:
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 */
}
 
D

Dan Pop

In said:
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
 
C

CBFalconer

Andrew said:
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.
 
F

Fred L. Kleinschmidt

Andrew said:
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.
 
S

Sean Kenwrick

Andrew said:
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
 
C

CBFalconer

Sean said:
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.
 
E

E. Robert Tisdale

Andrew said:
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.
 
J

Jack Klein

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

E. Robert Tisdale

Jack said:
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?
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.
Or is uninitialized. Or null.
Or points to allocated memory that has been free.


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;
}
 
J

Jack Klein

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.
But they all have "automatic storage".
The typical implementation of automatic storage is on the program stack.


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

Richard Heathfield

E. Robert Tisdale said:
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.

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

rahul dev

E. Robert Tisdale said:
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
of your executable.

-rd
 
C

Christian Bau

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?
 
J

Jared Dykstra

CBFalconer said:
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
tread.
 
J

Joona I Palaste

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...
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?
 
R

Richard Bos

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.

In fact, all your comments are highly system-specific.

Richard
 
A

August Derleth

Joona said:
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).
 

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
473,756
Messages
2,569,540
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top