473,659 Members | 2,690 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 #1
34 33107
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(c har) * n);


Not portably.

--
/-- Joona Palaste (pa*****@cc.hel sinki.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(c har) * 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(c har) * 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(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.

--
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 #4
In <65************ **************@ posting.google. com> an***********@c a.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(c har) * 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(c har) * 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.goo gle.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);


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(c har) * 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********@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 #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(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.

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(s izeof(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.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #10

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

Similar topics

3
3608
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
6892
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
2535
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
2357
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
4647
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
3046
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
8332
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
8627
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
7356
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
6179
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
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4335
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2750
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
1975
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.