473,795 Members | 3,157 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1755
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)

iD8DBQFDFvBFagV FX4UWr64RArtmAJ 9qCfsS65UXU74Pr +c7g7V41Xe5gQCe ONVE
j+dalVn2+yk0wJz mNDLnSuA=
=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 misunderstandin gs 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********@gma il.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.c om, 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_SIZ E);
...
free(p1);
...
p2 = malloc(SOME_SIZ E);

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_Keit h) 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
2498
by: David Scarlett | last post by:
Is the following code safe? SomeType *a, *b; /* Some code.... */ free(a);
72
3634
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
6875
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 anybody know how to write such a function? Regards, Prabhat
5
10472
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
6280
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 something;
13
3615
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. Now, suppose there is an array of more than one element need to be freed, as free() doesn't accept a argument indicating the size, how can
1
2142
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 the library <mcheck.h>. Now the very last bugs I seem to be incapable of eliminating are: - 0x000000000061f460 Free 387310 was never alloc'd 0x2aaaab053b53 - 0x000000000061f040 Free 387311 was never alloc'd 0x2aaaab053b53
10
8340
by: frakie | last post by:
Hi 'body, is there a method to check if a pointer is pointing a freed memory location?
58
4935
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
9672
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
9519
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
10437
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
10214
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
6780
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
5437
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
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3723
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
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.