473,500 Members | 1,943 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

validate pointer that was returned from malloc

Hi,

Is there a standard way to validate if a pointer points to memory that was
allocated by malloc?
TIA
Nov 14 '05 #1
21 2292
Bryan Bullard wrote:
Is there a standard way to validate if a pointer points to memory that was
allocated by malloc?


No.

--
Best regards,
Andrey Tarasevich

Nov 14 '05 #2
> Is there a standard way to validate if a pointer points to memory that was
allocated by malloc?


You would have to write your own wrapper for malloc for that one - that
might be fun. :)

Kristofer
Nov 14 '05 #3
Bryan Bullard wrote:
Is there a standard way
No.
to validate if a pointer points to memory that was allocated by malloc? cat onStack.c

#include <stdio.h>
#include <stdlib.h>

int onStack(void* p) {
return (p > (void*)&p);
}

int main(int argc, char* argv[]) {
char c;
char* p = &c;
//char* p = (char*)malloc(sizeof(char));
if (onStack(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 #4

"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote in message
news:cp**********@nntp1.jpl.nasa.gov...
Bryan Bullard wrote:
Is there a standard way


No.
to validate if a pointer points to memory that was allocated by malloc?

> cat onStack.c

#include <stdio.h>
#include <stdlib.h>

int onStack(void* p) {
return (p > (void*)&p);
}

int main(int argc, char* argv[]) {
char c;
char* p = &c;
//char* p = (char*)malloc(sizeof(char));
if (onStack(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, what I'm looking for is a way to determine if a pointer points to
a block that is "safe" to read.
Nov 14 '05 #5
Bryan Bullard wrote:
Bryan Bullard wrote:
Is there a standard way

[...]


Actually, what I'm looking for is a way to determine if a pointer points to
a block that is "safe" to read.


And you've been told that there's no standard way, which
is what you asked for. I've got a counter-question: If your
code is handed a junk pointer, what corrective action do you
expect it to take?

--
Er*********@sun.com

Nov 14 '05 #6
On Fri, 10 Dec 2004 22:08:57 GMT, in comp.lang.c , "Bryan Bullard"
<re****@to.group.com> wrote:

Actually, what I'm looking for is a way to determine if a pointer points to
a block that is "safe" to read.


There is still no standard way to do this. If the block points to memory
you didn't allocate, thats a coding error. If it points to memory you
deallocated, thats also a coding error. If it points to corrupted memory,
your programme is already dead, so its too late to worry...
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>
Nov 14 '05 #7

"Eric Sosman" <er*********@sun.com> wrote in message
news:cp**********@news1brm.Central.Sun.COM...
I've got a counter-question: If your
code is handed a junk pointer, what corrective action do you
expect it to take?


Something more graceful then core dump.
Nov 14 '05 #8
Thank you to everyone that posted.
Nov 14 '05 #9
On Fri, 10 Dec 2004 22:41:41 GMT, in comp.lang.c , "Bryan Bullard"
<re****@to.group.com> wrote:

"Eric Sosman" <er*********@sun.com> wrote in message
news:cp**********@news1brm.Central.Sun.COM...
I've got a counter-question: If your
code is handed a junk pointer, what corrective action do you
expect it to take?


Something more graceful then core dump.


Then you're out of luck. There's no standard way to detect memory
corruption.

The question you should probably be asking is "why would I ever get a bad
pointer, if I wrote my code carefully?"
Of course from a system-specific point of view there might be either a
coding hack of some sort or a 3rd party library which trapped bad memory
and handled it. That would be a topic for a unix or windows or whatever
programming group.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>
Nov 14 '05 #10
On Fri, 10 Dec 2004 11:34:20 -0600
Kristofer Pettijohn <kr*******@cybernetik.net> wrote:
Is there a standard way to validate if a pointer points to memory
that was allocated by malloc?


You would have to write your own wrapper for malloc for that one -
that might be fun. :)


This is still not guaranteed.

#include <stdlib.h>
#include <my_wrappers.h>

void foo(void)
{
char *ptr = my_malloc(5) /* allocated memory at address 0x1000 */
free(ptr); /* Oops, the wrong free was used */
ptr = my_malloc(5) /* allocated memory address is 0x0FFF, don't ask
why, it's just a screwy allocator */
ptr++;
my_print_valid(ptr); /* my_print_valid thinks this is object
returned by first my_malloc call, but it is really 1 byte in to memory
returned by second my_malloc call */
}

So it only works if your wrappers are always used, not if someone
forgets once.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #11
Bryan Bullard wrote:
Actually, what I'm looking for is a way to determine
if a pointer points to a block that is "safe" to read.


No.

It isn't "safe" to "read" from any uninitialized memory
whether allocated from the automatic of free storage.
If you use malloc to allocate free storage,
you need to initialize (write to) that storage
before you can read it. If you are worried about
a [non NULL] pointer to an invalid object,
about the only thing that you can do is write
a known valid bit pattern into some field of that object
that you can check before you attempt access the other fields:

#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>

typedef struct X {
unsigned
int pattern;
int other;
} X;

inline static
X X_create(int i) {
X x;
x.pattern = 0x55555555;
x.other = i;
return x;
}

inline static
void X_destroy(const X* p) {
X* q = (X*)p;
q->pattern = 0xAAAAAAAA;
}

inline static
bool X_valid(const X* p) {
return 0x55555555 == p->pattern;
}

inline static
int X_value(const X* p) {
return p->other;
}

int main(int argc, char* argv[]) {
X* p = (X*)malloc(sizeof(X));
*p = X X_create(13)
if (X_valid(p))
fprintf(stdout, "X_value(p) = %d\n", X_valid(p));
X_destroy(p);
free((void*)p);
return 0;
}
Nov 14 '05 #12
Bryan Bullard wrote:

Is there a standard way to validate if a pointer points to memory
that was allocated by malloc?


Yes. Remember the fact.

--
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 #13

"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote in message
news:cp**********@nntp1.jpl.nasa.gov...

....
If you are worried about
a [non NULL] pointer to an invalid object,
about the only thing that you can do is write
a known valid bit pattern into some field of that object
that you can check before you attempt access the other fields:


This is essentially what I've done. However, I would like to make sure that
the pointer is accessible before I check the pattern in the structure that
is pointed to. This is my issue.

....
Nov 14 '05 #14

"CBFalconer" <cb********@yahoo.com> wrote in message
news:41***************@yahoo.com...
Bryan Bullard wrote:

Is there a standard way to validate if a pointer points to memory
that was allocated by malloc?


Yes. Remember the fact.


And what would that fact be?
Nov 14 '05 #15
Bryan Bullard wrote:
"Eric Sosman" <er*********@sun.com> wrote in message
news:cp**********@news1brm.Central.Sun.COM...

I've got a counter-question: If your
code is handed a junk pointer, what corrective action do you
expect it to take?


Something more graceful then core dump.


That's not very specific, is it?

I posed the question because a core dump is usually
the best and most desirable outcome in a case like this.
Consider: There's not much corrective action you can
safely take, because there's no reason to believe the
bad pointer you've detected is the first bad pointer
the program has used. It may well have scribbled all
over memory before you had a chance to notice, and it
would be perilous to proceed on the basis of information
already known to be suspect. All you know is that the
program has gone off the rails, and badly -- a hard stop
will at least prevent the amok program from doing further
damage to disk files and the like, and a hard stop with
a core dump to facilitate post-mortem analysis is usually
welcome.

<off-topic>

A similar situation arises in multi-threaded programs,
where people are always asking how to respond to SIGSEGV
by terminating "only the offending thread" instead of the
entire process. Usually, they haven't really thought
about the situation.

</off-topic>

... and that's why I asked the question: to see if
you'd actually thought it through, and if so what you
expected to do about error recovery. "Something more
graceful than a core dump" doesn't give me a warm fuzzy
feeling about how much thought you've given the matter,
although I could be wrong about that. What are your
intentions?

--
Er*********@sun.com

Nov 14 '05 #16
"Bryan Bullard" <re****@to.group.com> writes:
"CBFalconer" <cb********@yahoo.com> wrote in message
news:41***************@yahoo.com...
Bryan Bullard wrote:
>
> Is there a standard way to validate if a pointer points to memory
> that was allocated by malloc?


Yes. Remember the fact.


And what would that fact be?


The fact that the pointer points to memory that was allocated by
malloc. (Presumably you also want to remember whether it's been
passed to free(), and deal with calloc() and realloc().)

There is no portable way to do what you want other than by carefully
keep track of everything yourself. Sorry if that's an unsatisfactory
answer, but it's the way it is.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #17
On Fri, 10 Dec 2004 23:16:00 GMT, in comp.lang.c , "Bryan Bullard"
<re****@to.group.com> wrote:

"CBFalconer" <cb********@yahoo.com> wrote in message
news:41***************@yahoo.com...
Bryan Bullard wrote:
>
> Is there a standard way to validate if a pointer points to memory
> that was allocated by malloc?


Yes. Remember the fact.


And what would that fact be?


That the memory was allocated by malloc.

Chuck means "remember that you allocated it, and you will have no problem
with its validity"

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>
Nov 14 '05 #18
On Fri, 10 Dec 2004 23:14:11 GMT, in comp.lang.c , "Bryan Bullard"
<re****@to.group.com> wrote:

"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote in message
news:cp**********@nntp1.jpl.nasa.gov...

...
If you are worried about
a [non NULL] pointer to an invalid object,
about the only thing that you can do is write
a known valid bit pattern into some field of that object
that you can check before you attempt access the other fields:


This is essentially what I've done. However, I would like to make sure that
the pointer is accessible before I check the pattern in the structure that
is pointed to. This is my issue.


ERT's method isn't guaranteed anyway. All bitpatterns could represent valid
memory, or some could be traps or otherwise invalid. F'rexample setting
uninitialised pointers to 0xFFFFF or 0xDEADBEEF might seem good, but both
might be valid addresses.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>
Nov 14 '05 #19
Bryan Bullard wrote:
E. Robert Tisdale wrote:
If you are worried about
a [non NULL] pointer to an invalid object,
about the only thing that you can do is write
a known valid bit pattern into some field of that object
that you can check before you attempt access the other fields:
This is essentially what I've done.
However, I would like to make sure that the pointer is accessible
before I check the pattern in the structure that is pointed to.


You can't.
This is my issue.


You might look into installing a signal handler
to handle Invalid memory reference (SIGSEGV).
But these are *not* really topical in comp.lang.c
so try a newsgroup specific to your operating system
and try your local documentation:

man 7 signal

for example.
Nov 14 '05 #20
Eric Sosman <er*********@sun.com> writes:
Bryan Bullard wrote:
"Eric Sosman" <er*********@sun.com> wrote in message
news:cp**********@news1brm.Central.Sun.COM...

I've got a counter-question: If your
code is handed a junk pointer, what corrective action do you
expect it to take?


Something more graceful then core dump.


That's not very specific, is it?

I posed the question because a core dump is usually
the best and most desirable outcome in a case like this.
Consider: There's not much corrective action you can
safely take, because there's no reason to believe the
bad pointer you've detected is the first bad pointer
the program has used. It may well have scribbled all
over memory before you had a chance to notice, and it
would be perilous to proceed on the basis of information
already known to be suspect. All you know is that the
program has gone off the rails, and badly -- a hard stop
will at least prevent the amok program from doing further
damage to disk files and the like, and a hard stop with
a core dump to facilitate post-mortem analysis is usually
welcome.


Agreed. In fact, the best corrective action you can take is to fix
the bug that caused the bad pointer in the first place. A core dump
is specifically intended to help you do that.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #21
On Fri, 10 Dec 2004 21:40:23 +0000, Flash Gordon <sp**@flash-gordon.me.uk>
wrote:
On Fri, 10 Dec 2004 11:34:20 -0600
Kristofer Pettijohn <kr*******@cybernetik.net> wrote:
> Is there a standard way to validate if a pointer points to memory
> that was allocated by malloc?


You would have to write your own wrapper for malloc for that one -
that might be fun. :)


This is still not guaranteed.

#include <stdlib.h>
#include <my_wrappers.h>

void foo(void)
{
char *ptr = my_malloc(5) /* allocated memory at address 0x1000 */
free(ptr); /* Oops, the wrong free was used */


If you want to violate standards, you can define free() as a modified
wrapper to call my_free() instead. While it might work on some compilers,
it's not something that should be used for portable code.

Nov 14 '05 #22

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

Similar topics

2
1597
by: Yossarian | last post by:
Hi, I'm a bit confused about something, hopefully someone can put me straight. I'd like to be able to call a function which takes a pointer to pointer, have that function allocate memory and...
20
6165
by: joe | last post by:
Hi all! I just have quick, possibly stupid question.... is it possible to do the following: int func(){ int *pointer; foo(pointer); } int foo(int *pointer){
16
2262
by: junky_fellow | last post by:
According to Section A6.6 Pointers and Integers (k & R) " A pointer to one type may be converted to a pointer to another type. The resulting pointer may cause addressing exceptions if the...
42
5852
by: junky_fellow | last post by:
Consider an implementation that doesn't use all bits 0 to represent a NULL pointer. Let the NULL pointer is represented by 0x12345678. On such an implementation, if the value of NULL pointer is...
14
2627
by: Mirko | last post by:
Hello, I'm new to this list and to Usenet in general, so please forgive (and advice) me, if I do something wrong. Anyway. I am a bit confused, because I always thought one _should_ explicitly...
48
2114
by: yezi | last post by:
Hi, all: I want to record some memory pointer returned from malloc, is possible the code like below? int memo_index; int i,j; char *tmp; for (i=0;i<10;i++){
5
4307
by: Johs32 | last post by:
I have a struct "my_struct" and a function that as argument takes a pointer to this struct: struct my_struct{ struct my_struct *new; }; void my_func(struct my_struct *new); I have read...
5
8064
by: mkaushik | last post by:
Hi everyone, Im just starting out with C++, and am curious to know how "delete <pointer>", knows about the number of memory locations to free. I read somewhere that delete frees up space...
20
1770
by: svata | last post by:
Hello there, after some time of pondering I come to some solution which would suit me best. Please correct, if I am wrong. Function has two parameters. A string array, better said a pointer to...
0
7018
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...
0
7182
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,...
1
6906
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7397
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...
1
4923
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...
0
4611
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...
0
1430
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 ...
1
672
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
316
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...

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.