473,320 Members | 1,821 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,320 software developers and data experts.

Test if pointer points to allocated memory

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);
Nov 14 '05 #1
34 33016
Andrew <an***********@ca.com> 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 (pa*****@cc.helsinki.fi) ------------- 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
Nov 14 '05 #2
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
Nov 14 '05 #3
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.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #4
In <65**************************@posting.google.com > an***********@ca.com (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: Da*****@ifh.de
Nov 14 '05 #5


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
Nov 14 '05 #6

"Andrew" <an***********@ca.com> wrote in message
news:65**************************@posting.google.c om...
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
Nov 14 '05 #7
Sean Kenwrick wrote:
"Andrew" <an***********@ca.com> 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 (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #8
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.

Nov 14 '05 #9
On Wed, 21 Jan 2004 19:17:17 -0800, "E. Robert Tisdale"
<E.**************@jpl.nasa.gov> 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/~a...FAQ-acllc.html
Nov 14 '05 #10
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;
}
Nov 14 '05 #11
On Wed, 21 Jan 2004 21:27:17 -0800, "E. Robert Tisdale"
<E.**************@jpl.nasa.gov> 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/~a...FAQ-acllc.html
Nov 14 '05 #12
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 : bi****@eton.powernet.co.uk
"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
Nov 14 '05 #13
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote in message news:<40**************@jpl.nasa.gov>...
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
of your executable.

-rd
Nov 14 '05 #14
In article <40**************@jpl.nasa.gov>,
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> 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.
Nov 14 '05 #15
In article <6d**************************@posting.google.com >,
ra***********@hotmail.com (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
of your executable.

-rd

Nov 14 '05 #16
CBFalconer <cb********@yahoo.com> wrote in message news:<40***************@yahoo.com>...
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
tread.

---
Jared Dykstra
http://www.bork.org/~jared
Nov 14 '05 #17
Christian Bau <ch***********@cbau.freeserve.co.uk> scribbled the following:
In article <6d**************************@posting.google.com >,
ra***********@hotmail.com (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 (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"You could take his life and..."
- Mirja Tolsa
Nov 14 '05 #18
ra***********@hotmail.com (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.

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

Richard
Nov 14 '05 #19
Joona I Palaste wrote:
Christian Bau <ch***********@cbau.freeserve.co.uk> scribbled the following:
In article <6d**************************@posting.google.com >,
ra***********@hotmail.com (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?


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.
Nov 14 '05 #20
rahul dev wrote:
<E.**************@jpl.nasa.gov> wrote
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
of your executable.


This sort of answer illustrates the danger of allowing Trollsdale
posts to go unchallenged. brk/sbrk are not part of the C
standard, and their actions (if present) are non-portable and thus
immaterial on c.l.c. Everybody should be aware that ANYTHING
written by Tisdale aka Trollsdale is immediately suspect and
probably nonsense.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #21
CBFalconer <cb********@yahoo.com> scribbled the following:
rahul dev wrote:
<E.**************@jpl.nasa.gov> wrote
> 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
of your executable.

This sort of answer illustrates the danger of allowing Trollsdale
posts to go unchallenged. brk/sbrk are not part of the C
standard, and their actions (if present) are non-portable and thus
immaterial on c.l.c. Everybody should be aware that ANYTHING
written by Tisdale aka Trollsdale is immediately suspect and
probably nonsense.


It was rahul dev, not Trollsdale, who wrote all that crap about brk/
sbrk and "_end" symbols.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"I am looking for myself. Have you seen me somewhere?"
- Anon
Nov 14 '05 #22
In <bu**********@oravannahka.helsinki.fi> Joona I Palaste <pa*****@cc.helsinki.fi> writes:
Christian Bau <ch***********@cbau.freeserve.co.uk> scribbled the following:
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?


Most computers don't have a kernel (they are very small chips used in
embedded control applications; your PC probably contains several of them).

OTOH, they don't have hosted C implementations, either, so Christian's
point about malloc on kernel-less computers is moot: freestanding
implementations need not provide malloc at all.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #23
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?

// 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");
}


C:\Program Files\DevStudio\SharedIDE\bin\Debug>new
p probably points to a character in automatic storage.

--
pete
Nov 14 '05 #24
Joona I Palaste wrote:
CBFalconer <cb********@yahoo.com> scribbled the following:
rahul dev wrote:
<E.**************@jpl.nasa.gov> wrote
> 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
of your executable.

This sort of answer illustrates the danger of allowing Trollsdale
^^^^^^^^^^^^^^^^^^^
posts to go unchallenged. brk/sbrk are not part of the C
standard, and their actions (if present) are non-portable and thus
immaterial on c.l.c. Everybody should be aware that ANYTHING
written by Tisdale aka Trollsdale is immediately suspect and
probably nonsense.


It was rahul dev, not Trollsdale, who wrote all that crap about brk/
sbrk and "_end" symbols.


But he was triggered by the Trollsdale junk. I consider him a
poor sucker trolled by Trollsdale. See underlined.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 14 '05 #25
In <Fr******************@fe02.usenetserver.com> August Derleth <se*@sig.now> writes:
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. ;) )


Nope, it is a lot more than that. It provides many of the services
offered by the kernels of more sophisticated OSs; it's just that many
of them are extremely poorly implemented (console I/O very slow, serial
I/O unreliable at "high" speeds because is not interrupt driven) and
others are designed with a complete lack of security concerns in mind.

Actually version 2 was not so bad, given the hardware it was supposed to
run on. Things started to get bad by the time IBM introduced the AT/286
but the OS kept treating the machine as a fast 8086 and became absolutely
ludicrous when the AT/386 was treated as an even faster 8086 by the OS.
Yet, the OS design remained unchanged until its official death, in the
Pentium I era.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #26
In <40***************@yahoo.com> CBFalconer <cb********@yahoo.com> writes:
rahul dev wrote:
<E.**************@jpl.nasa.gov> wrote
> 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
of your executable.


This sort of answer illustrates the danger of allowing Trollsdale
posts to go unchallenged. brk/sbrk are not part of the C
standard, and their actions (if present) are non-portable and thus
immaterial on c.l.c. Everybody should be aware that ANYTHING
written by Tisdale aka Trollsdale is immediately suspect and
probably nonsense.


By what kind of logic can Trollsdale be made responsible for the
nonsense written by other people, rahul dev, in this case?

C'mon, if you engage your brain, I'm sure you can tell the difference
between the lines prefixed by one '>' and those with no prefix at all.
You may even be able to decode the meaning of the line:

<E.**************@jpl.nasa.gov> wrote

appearing at the beginning of a post (right after the headers): it
means that all the lines prefixed by a single '>' have been written
by Trollsdale, while those with no prefix have been written by the
poster whose name appears in the From header of the post (and in the
signature block, if present).

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #27
In <40***************@yahoo.com> CBFalconer <cb********@yahoo.com> writes:
Joona I Palaste wrote:
CBFalconer <cb********@yahoo.com> scribbled the following:
> rahul dev wrote:
>> <E.**************@jpl.nasa.gov> wrote
>> > 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
>> of your executable.

> This sort of answer illustrates the danger of allowing Trollsdale
> ^^^^^^^^^^^^^^^^^^^
> posts to go unchallenged. brk/sbrk are not part of the C
> standard, and their actions (if present) are non-portable and thus
> immaterial on c.l.c. Everybody should be aware that ANYTHING
> written by Tisdale aka Trollsdale is immediately suspect and
> probably nonsense.


It was rahul dev, not Trollsdale, who wrote all that crap about brk/
sbrk and "_end" symbols.


But he was triggered by the Trollsdale junk. I consider him a
poor sucker trolled by Trollsdale. See underlined.


A perfect non-sequitur. Your own comments apply to the text posted by
rahul dev and there is no way to blame that text on Trollsdale's advice,
especially considering that he was explicitly saying that it was *not*
based on the C standard.

Your lame attempt to save your ass from your previous mistake fools no
one. Believe me, there is no substitute for engaging your brain before
posting.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #28
an***********@ca.com (Andrew) wrote in message news:<65**************************@posting.google. com>...
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);


Well, if you need to do this, there is one portable option. You could
"wrap" malloc, calloc, realloc, and free, and keep track of
the things allocated/freed. Of course, this only works for things
allocated under your control, which may not always be true of
all dynamically allocated memory you encounter (e.g. stuff from
libraries not owned by you). Anyway, the following might work
for you:

example program fragment, assumes you have some static hash
table accessed through the hash functions which store or
retrieve pointer values.

void *my_malloc(size_t size)
{
void *tmp = malloc(size);

if (tmp != NULL) {
hash_enter(tmp);
}

return tmp;
}

void my_free(void *ptr)
{
if (ptr != NULL) {
hash_remove(ptr);
free(ptr);
}
}

int ptr_was_allocated(void *ptr)
{
if (ptr != NULL && hash_contains(ptr)) {
return 1;
}
else {
return 0;
}
}

If the above doesn't suit you, you are out of luck in portable
C AFAIK. But if you are willing to use platform specific extensions,
you may have some options. If so, ask in a group dedicated to
your platform. Or you could leave such checking of
pointers out of your code, and use the tools available for your
platform while testing to detect invalid memory accesses -- for example
valgrind/electric fence/bounds checker/Purify/etc.

Good luck.

-David
Nov 14 '05 #29
Dan Pop wrote:
In <Fr******************@fe02.usenetserver.com> August Derleth <se*@sig.now> writes:

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

Nope, it is a lot more than that. It provides many of the services
offered by the kernels of more sophisticated OSs; it's just that many
of them are extremely poorly implemented (console I/O very slow, serial
I/O unreliable at "high" speeds because is not interrupt driven) and
others are designed with a complete lack of security concerns in mind.


Hm. I suppose I knew that (I do assembly-level DOS programming on
occasion, nearly always for 80386s or higher), but I tried to subsume it
under the rubric of `interrupt handler'. In other words, I was being
somewhat facetious and trying to imply that anything like PC-DOS,
MS-DOS, or DR-DOS (or any of the lesser-known clones) is /not/ a Real OS
by my (Unix-informed) standard. ;)

It's also interesting to hear just how broken PC-DOS truly was. Wasn't
that IBM's in-house project? No wonder they embraced Linux so quickly:
Moderately code must make them downright ecstatic, when compared to what
they'd have done on their own. ;)

Actually version 2 was not so bad, given the hardware it was supposed to
run on. Things started to get bad by the time IBM introduced the AT/286
but the OS kept treating the machine as a fast 8086 and became absolutely
ludicrous when the AT/386 was treated as an even faster 8086 by the OS.
Yet, the OS design remained unchanged until its official death, in the
Pentium I era.
Bah. Bogosity and cruft, taken to an absurd degree. I can understand
(maybe) not using the half-baked extra features introduced in the 80286,
but not jumping with both feet on the 80386's 32-bit addressing and
general strides in the direction of becoming a Real Architecture?
Mind-boggling.

(I consider the 8086 to be an abortion of a design, and the 80386
Intel's semi-awakening to the world of ISA sanity. Nothing as pretty as
a VAX or even a Motorola 68000, but not nearly as painful to program
assembly for.)

Dan

--
My address is yvoregnevna gjragl-guerr gjb-gubhfnaq guerr ng lnubb qbg pbz
Note: Rot13 and convert spelled-out numbers to numerical equivalents.
Nov 14 '05 #30
On 21 Jan 2004 08:25:57 -0800,
Andrew <an***********@ca.com> wrote
in Msg. <65**************************@posting.google.com >
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);


I'm entering this thread a bit late, and therefor it's quite likely that
someone already made this sugegstion:

Why don't you initialize the pointer variable in question as NULL, and
test if it is non-NULL when in doubt? If you want to re-use the variable,
you must set it to NULL after freeing it. Of course this method has the
obvious limitations, but I use it all the time and am very satisfied.

I'm sure you've already been instructed to use

p = malloc(n * sizeof *p)

instead of doing it the way quoted above. The cast hides a possible bug,
and sizeof(char) is just a complicated way of writing 1. The generally
accepted method works with all pointer types, discloses failure to include
stdlib.h, and is less verbose.

--Daniel
--
"With me is nothing wrong! And with you?" (from r.a.m.p)
Nov 14 '05 #31
Daniel Haude wrote:
On 21 Jan 2004 08:25:57 -0800,
Andrew <an***********@ca.com> wrote
in Msg. <65**************************@posting.google.com >
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);

I'm entering this thread a bit late, and therefor it's quite likely that
someone already made this sugegstion:

Why don't you initialize the pointer variable in question as NULL, and
test if it is non-NULL when in doubt? If you want to re-use the variable,
you must set it to NULL after freeing it. Of course this method has the
obvious limitations, but I use it all the time and am very satisfied.

[ snip ]

Limitations indeed. If you know that you are careful enough to NULL a
pointer after freeing it, then what is the point of later checking it
for NULL? What will we do if it is not NULL? Error out?

On most modern 32-bit architectures a pointer value has 4 billion
possibilities, NULL and all the others. The C programmer can examine the
pointer value to determine whether it is NULL or not. Beyond that, its
validity is not knowable.

--
Joe Wright mailto:jo********@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---

Nov 14 '05 #32
On Sun, 25 Jan 2004 12:41:39 -0500,
Joe Wright <jo********@comcast.net> wrote
in Msg. <PL********************@comcast.com>
Limitations indeed. If you know that you are careful enough to NULL a
pointer after freeing it, then what is the point of later checking it
for NULL? What will we do if it is not NULL? Error out?


That depends on whether we expect the pointer to be pointing at useable
storage area or not.

--Daniel

--
"With me is nothing wrong! And with you?" (from r.a.m.p)
Nov 14 '05 #33
Daniel Haude wrote:

On Sun, 25 Jan 2004 12:41:39 -0500,
Joe Wright <jo********@comcast.net> wrote
in Msg. <PL********************@comcast.com>
Limitations indeed. If you know that you are careful enough to NULL a
pointer after freeing it, then what is the point of later checking it
for NULL? What will we do if it is not NULL? Error out?


That depends on whether we expect the pointer to be pointing at useable
storage area or not.

It doesn't matter what you expect. NULL does not point to useable
storage. You can't tell whether any other pointer value does. Think
about it.
--
Joe Wright http://www.jw-wright.com
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #34
On Mon, 26 Jan 2004 00:19:04 GMT,
Joe Wright <jo********@earthlink.net> wrote
in Msg. <40**********@earthlink.net>
It doesn't matter what you expect. NULL does not point to useable
storage. You can't tell whether any other pointer value does. Think
about it.


Don't worry, I already know all about it. If you think that I think that
any non-NULL pointer points to allocated memory, you're mistaken. Remember
that I pointed out the "obvious limitations" of this simple method right
at the beginning.

If one interprets the OP literally as a request for a method that, when
fed ANY pointer, can tell if it points to allocated storage, then of
course it's not sufficient to just test against NULL. But then such a
method would be at best of academic interest, but rather useless for
practical purposes (unless you're wrizing a debugger).

--Daniel

--
"With me is nothing wrong! And with you?" (from r.a.m.p)
Nov 14 '05 #35

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

Similar topics

3
by: Tony Johansson | last post by:
Hello Experts!! When you instansiate varaibles(object) you can do so in four different scops which are. Within a block which is called Local or block scope . Within a function which is called...
3
by: mandark_br | last post by:
I have a function that returns a int pointer to a allocated memory. How I know the size of this allocated memory? Compiler = gcc Ex.: int main(void) {
3
by: Santh | last post by:
Hi, I have a bulk of data available in safearray pointer. I want to copy that data to another pointer. I tried using malloc for new variable and memcopy. But due to virtual memory restrictions the...
19
by: pinkfloydhomer | last post by:
Please read the example below. I'm sorry I couldn't make it smaller, but it is pretty simple. When client code is calling newThingy(), it is similar to malloc: the client gets a pointer to a...
74
by: ballpointpenthief | last post by:
If I have malloc()'ed a pointer and want to read from it as if it were an array, I need to know that I won't be reading past the last index. If this is a pointer to a pointer, a common technique...
26
by: Bill Reid | last post by:
Bear with me, as I am not a "professional" programmer, but I was working on part of program that reads parts of four text files into a buffer which I re-allocate the size as I read each file. I...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.