473,836 Members | 2,179 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(c har) * n);
Nov 14 '05
34 33174
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(s izeof(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(s izeof(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.l earn.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(s izeof(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.pow ernet.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.nas a.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(s izeof(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***********@h otmail.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********@yah oo.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(c har) * 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***********@h otmail.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.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"You could take his life and..."
- Mirja Tolsa
Nov 14 '05 #18
ra***********@h otmail.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***********@h otmail.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

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

Similar topics

3
3616
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 function scope. Whithin a class which is called class scope. Outside a function which is called global or file scope. Now to my question when you allocate memory dynamically you can't say
3
6902
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
2545
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 allocation failed. This is because the system memory can not allocate another volume of memory. My requirement is , without allocating the new memory, how can I copy the data from safe array to my variable. Since after copying I dont need the...
19
2376
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 chunk of memory that it can use for it's own purposes. But on the "library" side, I want to be able to do some book-keeping for each memory block that I hand out. I want some "hidden" meta-data (that I keep in struct Container) to be associated...
74
4710
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 seems to be setting a NULL pointer to the end of the list, and here we know that the allocated memory has been exhausted. All good. When this is a pointer to another type, say int, I could have a variable that records how much memory is being...
26
3070
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 read some of the items from the bottom up of the buffer, and some from the top down, moving the bottom items back to the new re-allocated bottom on every file read. Then when I've read all four files, I sort the top and bottom items separately...
0
9810
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9656
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10821
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10241
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9358
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7773
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5812
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4443
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4001
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.