473,889 Members | 1,957 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 33189
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(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.


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********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #21
CBFalconer <cb********@yah oo.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(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.

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.hel sinki.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**********@o ravannahka.hels inki.fi> Joona I Palaste <pa*****@cc.hel sinki.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(s izeof(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********@yah oo.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(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.

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********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!

Nov 14 '05 #25
In <Fr************ ******@fe02.use netserver.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********@yah oo.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(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.


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********@yah oo.com> writes:
Joona I Palaste wrote:
CBFalconer <cb********@yah oo.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(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.

> 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***********@c a.com (Andrew) wrote in message news:<65******* *************** ****@posting.go ogle.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(c har) * 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_allocat ed(void *ptr)
{
if (ptr != NULL && hash_contains(p tr)) {
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.use netserver.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

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
6903
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
2546
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
2378
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
4725
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
3077
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
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
11203
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
10794
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10443
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
9612
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
7999
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
6029
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4650
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
3
3257
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.