473,320 Members | 2,073 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.

Detecting freed memory

Rob
int *p;

p = malloc(1);

free(p);

/* */
In the above code, how do I detect that variable p points to nothing?
In other words, how do I detect a freed memory pointer, as opposed to a
pointer that points to allocated memory?

Nov 15 '05 #1
6 1725
There is no general way to do this. One way is to write your own
wrappers around malloc and free and include different signatures in the
buffer that can be checked.

Microsoft Visual C++ compiler does something similar in a Debug build.
When a buffer is freed, it copies a known signature pattern in all the
bytes of the buffer.

--
EventStudio 2.5 - http://www.EventHelix.com/EventStudio
Generate Sequence Diagrams in PDF and Word EMF from plain text input

Nov 15 '05 #2
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Rob wrote:
int *p;

p = malloc(1);

free(p);

/* */
In the above code, how do I detect that variable p points to nothing?
In the above code, you don't (and can't) "detect that variable p points to nothing".
In other words, how do I detect a freed memory pointer, as opposed to a
pointer that points to allocated memory?


You detect it by not using it. It's your code, and you are assumed to know what
you are doing. You are in control; you allocate the pointer variable, fill it
with a pointer to storage, and then subsequently dispose of the storage. You do
this explicitly. It behoves you, as a competent programmer to then /not/
dereference the pointer variable that you /know/ no longer points to storage.

Having said that, there are techniques that /you/ can employ that will permit
you to be lax in tracking whether or not pointer variables point at storage. One
such technique is to assign the pointer variable a NULL value whenever the
pointer no longer points to allocated storage. Something like

{
char *p = NULL;

p = malloc(1);

free(p); p = NULL;
}

With this, a simple test before dereferencing will suffice...

if (p) *p = 100;
I'm sure you can come up with other methods of protecting yourself when you are
less than thorough in your handling of pointer variables.

- --
Lew Pitcher
IT Specialist, Enterprise Data Systems,
Enterprise Technology Solutions, TD Bank Financial Group

(Opinions expressed are my own, not my employers')
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (MingW32)

iD8DBQFDFvBFagVFX4UWr64RArtmAJ9qCfsS65UXU74Pr+c7g7 V41Xe5gQCeONVE
j+dalVn2+yk0wJzmNDLnSuA=
=KwfF
-----END PGP SIGNATURE-----
Nov 15 '05 #3
Rob

Lew Pitcher wrote:
You detect it by not using it. It's your code, and you are assumed to know what
you are doing. You are in control; you allocate the pointer variable, fill it
with a pointer to storage, and then subsequently dispose of the storage. You do
this explicitly. It behoves you, as a competent programmer to then /not/
dereference the pointer variable that you /know/ no longer points to storage.


You are right. I asked the question because I was trying to implent
safety checks on functions and abort the program if it did something
illegal such as trying to access an illegal pointer. It seems this is
too much trouble, so I'll just go with the "be a competent programmer"
approach. :)

Nov 15 '05 #4

Rob wrote:
Lew Pitcher wrote:
You detect it by not using it. It's your code, and you are assumed to know what
you are doing. You are in control; you allocate the pointer variable, fill it
with a pointer to storage, and then subsequently dispose of the storage. You do
this explicitly. It behoves you, as a competent programmer to then /not/
dereference the pointer variable that you /know/ no longer points to storage.


You are right. I asked the question because I was trying to implent
safety checks on functions and abort the program if it did something
illegal such as trying to access an illegal pointer. It seems this is
too much trouble, so I'll just go with the "be a competent programmer"
approach. :)


But of course, you will make mistakes in a very large program...
There will be misunderstandings about who frees what, less than
competent programming somewhere, etc. It is nice
to have external tools to help diagnose such, as they often show
up in subtle ways. Tools vary with platform, and thus aren't on
topic here, but include stuff like purify/valgrind/electic
fence/mpatrol/
dmalloc/setting MALLOC_CHECK_=2/etc.

-David

Nov 15 '05 #5
>int *p;

p = malloc(1);

free(p); p; /* possible smegmentation fault here */
/* */
In the above code, how do I detect that variable p points to nothing?
You can't even TRY: doing anything with the value of p invokes the
wrath of undefined behavior. You might try setting p to NULL
immediately after the free() call, but *DO NOT* assume that the
fact that it's not null means it points somewhere valid unless you
are sure you've coded it that way. Why? Code like:

destructor(p); /* free p and its associated buffers */

cannot set p to NULL in the calling function, assuming destructor()
is an actual function. More often, a function cannot set all of
the copies of the pointer it's freeing to NULL because it doesn't
now where the copies are.

In other words, how do I detect a freed memory pointer, as opposed to a
pointer that points to allocated memory?


Keep track of it yourself.

Gordon L. Burditt
Nov 15 '05 #6
"EventHelix.com" <ev********@gmail.com> writes:
There is no general way to do this.
To do what? Please provide context; don't assume that your readers
can easily see the parent article, or even the subject header.

If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.

The parent article asked about how to detect, after a call to free(p),
that p is no longer a valid pointer. (Quick answer: you can't.)
One way is to write your own
wrappers around malloc and free and include different signatures in the
buffer that can be checked.

Microsoft Visual C++ compiler does something similar in a Debug build.
When a buffer is freed, it copies a known signature pattern in all the
bytes of the buffer.


It would also have to initialize newly malloc()ed memory with some
other pattern. Also, it can't easily handle cases like this:

p1 = malloc(SOME_SIZE);
...
free(p1);
...
p2 = malloc(SOME_SIZE);

After the second malloc(), p2 might very well point to the same chunk
of memory that p1 pointed to. p1 will appear to point to valid
memory; there's no good way to detect that this is merely accidental.

Tricks like writing 0xDEADBEEF into uninitialized memory can catch
some problems, but they can't catch everything.

--
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 15 '05 #7

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

Similar topics

73
by: David Scarlett | last post by:
Is the following code safe? SomeType *a, *b; /* Some code.... */ free(a);
72
by: ravi | last post by:
I have a situation where i want to free the memory pointed by a pointer, only if it is not freed already. Is there a way to know whether the memory is freed or not?
9
by: prabhat143 | last post by:
Hi, I was recently asked to write a function in C that would detect if memory is corrupted. I had no clue about the solution but what I believe is that the solution is not complicated. Does...
5
by: Thor W Hammer | last post by:
Hello all, Is it possible to find out if a script is freed? This is actual when having a pointer to a function and should determine if it is freed so we don't call it and get error.. TWH
25
by: junky_fellow | last post by:
Is there any way by which the overflow during addition of two integers may be detected ? eg. suppose we have three unsigned integers, a ,b, c. we are doing a check like if ((a +b) > c) do...
13
by: lovecreatesbeauty | last post by:
/* How do free() know how many elements should be freed in a dynamic array? When free a single variable, the amount of byte of memory can be retrieved from the type of variable itself. ...
1
by: lars.uffmann | last post by:
Hello everyone! I just debugged a pretty huge project, eliminating basically every memory leak that would occur with the current configuration files, at least according to the mtrace() tool from...
10
by: frakie | last post by:
Hi 'body, is there a method to check if a pointer is pointing a freed memory location?
58
by: sh.vipin | last post by:
is there any way to find out number of bytes freed on a particular free() call in C
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: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
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: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
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.