473,386 Members | 1,698 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,386 software developers and data experts.

Calling free() on an uninitialised pointer?

Hi,

If I call free() with a uninitialised pointer, will the program
state become undefined, or will free() return harmlessly?

Incidentally, is there a way in Standard C to determine
weather a pointer points to a valid block of allocated
memory?

Thanks for your time.

Dec 4 '05 #1
13 4956
santosh wrote:
If I call free() with a uninitialised pointer, will the program
state become undefined, or will free() return harmlessly?
a program that does this exhibits undefined behaviour. It *may*
return harmlessly or give a segmentation error or something even
nastier. Don't ever do this.

what is safe is:-
p = NULL;
free(p);
Incidentally, is there a way in Standard C to determine
weather a pointer points to a valid block of allocated
memory?


no
--
Nick Keighley

I don't use drugs, my dreams are frightening enough. --M. C. Escher

Dec 4 '05 #2
santosh a écrit :
Hi,

If I call free() with a uninitialised pointer, will the program
state become undefined, or will free() return harmlessly?
Undefined behaviour. A serious bug. Don't do that. Never.
Incidentally, is there a way in Standard C to determine
weather a pointer points to a valid block of allocated
memory?


Make it point to NULL by default or once free() has been performed. I
recommend this construction :

free(p), p = NULL;

It makes it easy to test, and it happens that free (NULL) is defined and
harmless.

--
A+

Emmanuel Delahaye
Dec 4 '05 #3
In article <11*********************@g49g2000cwa.googlegroups. com>,
"santosh" <sa*********@gmail.com> wrote:
Hi,

If I call free() with a uninitialised pointer, will the program
state become undefined, or will free() return harmlessly?


First, it is undefined behavior, so _anything_ can happen. Especially,
it might return harmlessly every time you do this while you are
developping your program, and the first time it is used seriously it
could crash the computer it is running on and cause considerable
financial damage. Don't do this.

What exactly happens depends on your implementation. The value of an
uninitialised pointer variable might by great coincidence be the same as
some pointer variable that was initialised by calling malloc. In that
case, calling free () will free that pointer, with likely harmful
consequences. That is not as unlikely as it seems, because an
uninitialised variable might be kept in a register that happens to
contain another completely unrelated variable of the calling function.
Dec 4 '05 #4
At about the time of 12/4/2005 2:17 AM, santosh stated the following:
Hi,

If I call free() with a uninitialised pointer, will the program
state become undefined, or will free() return harmlessly?
Maybe, maybe not. The behavior is undefined. Undefined meaning that
*ANYTHING* can happen, including your harddisk being reformatted (Which
is admittidly an extream case).
Incidentally, is there a way in Standard C to determine
weather a pointer points to a valid block of allocated
memory?
What I do is initialize all pointers to NULL when my program starts and
on entries to functions right in the initialzation section. This is a
good practice as it gives you a known starting point to go from.

int ptest(int size)
{
void *p;

p = NULL;
p = malloc(size);
if (p == NULL) return(-1);
/* perform some action here */
free(p);
return(0);
}

In this case here, p can never have an unknown value. If the call to
malloc fails, then malloc returns NULL, which can be tested for. Get
into the habbit of setting all your pointers to NULL before and after
you use them.
Thanks for your time.


--
Daniel Rudy

Email address has been base64 encoded to reduce spam
Decode email address using b64decode or uudecode -m

Why geeks like computers: look chat date touch grep make unzip
strip view finger mount fcsk more fcsk yes spray umount sleep
Dec 4 '05 #5
santosh wrote:
Hi,

If I call free() with a uninitialised pointer, will the program
state become undefined, or will free() return harmlessly?
Undefined behavior. You can call free() once and only once on a pointer
value returned by malloc & company. You can free(NULL) with no effect.
Incidentally, is there a way in Standard C to determine
weather a pointer points to a valid block of allocated
memory?
There is no way to determine by inspection the validity of any pointer
value. The only pointer value that you are guaranteed to know something
about is NULL and that it doesn't 'point' to anything.
Thanks for your time.

I've never had any real problem with the malloc()/free() stuff probably
because of programming habit. I always write the beginning and end of
functions at the same time. For example I begin a generic program with..

#include <stdio.h>

int main(void) {

return 0;
}

...and only then, fill it in with code. I tend to do the same with
malloc/free and fopen/fclose. Properly written, whether to free or
fclose is not the question, just do it.

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Dec 4 '05 #6
Emmanuel Delahaye wrote:
santosh a écrit :
Hi,

If I call free() with a uninitialised pointer, will the program
state become undefined, or will free() return harmlessly?

Undefined behaviour. A serious bug. Don't do that. Never.
Incidentally, is there a way in Standard C to determine
weather a pointer points to a valid block of allocated
memory?

Make it point to NULL by default or once free() has been performed. I
recommend this construction :

free(p), p = NULL;

It makes it easy to test, and it happens that free (NULL) is defined and
harmless.


Unfortunately, there are cases where doing so will mask a logic error
wherein otherwise a pointer would be free()-ed twice. So be careful.

HTH,
--ag

--
Artie Gold -- Austin, Texas
http://goldsays.blogspot.com
http://www.cafepress.com/goldsays
"If you have nothing to hide, you're not trying!"
Dec 4 '05 #7
"santosh" <sa*********@gmail.com> writes:
If I call free() with a uninitialised pointer, will the program
state become undefined, or will free() return harmlessly?


This is, of course undefined behavior, but not because of the call to
free(). Any attempt to evaluate an uninitialized pointer variable
invokes undefined behavior. For example:

int *ptr; /* uninitialized */
if (ptr == NULL) ...; /* undefined behavior */

Realistically, the call to free() is more likely to cause something
bad to happen than the evaluation of the argument.

--
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.
Dec 4 '05 #8
On 2005-12-04, Artie Gold <ar*******@austin.rr.com> wrote:
Emmanuel Delahaye wrote:
santosh a écrit :
Hi,

If I call free() with a uninitialised pointer, will the program
state become undefined, or will free() return harmlessly?

Undefined behaviour. A serious bug. Don't do that. Never.
Incidentally, is there a way in Standard C to determine
weather a pointer points to a valid block of allocated
memory?

Make it point to NULL by default or once free() has been performed. I
recommend this construction :

free(p), p = NULL;

It makes it easy to test, and it happens that free (NULL) is defined and
harmless.


Unfortunately, there are cases where doing so will mask a logic error
wherein otherwise a pointer would be free()-ed twice. So be careful.


it'll mask it or solve it? setting it to null guarantees that it won't
be freed twice, so this is hardly a "mask" - it actually changes the
logic to prevent the error
Dec 4 '05 #9
Keith Thompson wrote:
"santosh" <sa*********@gmail.com> writes:
If I call free() with a uninitialised pointer, will the program
state become undefined, or will free() return harmlessly?


This is, of course undefined behavior, but not because of the call to
free(). Any attempt to evaluate an uninitialized pointer variable
invokes undefined behavior. For example:

int *ptr; /* uninitialized */
if (ptr == NULL) ...; /* undefined behavior */

Realistically, the call to free() is more likely to cause something
bad to happen than the evaluation of the argument.


Thank you all for your clear replies.

To sum up, if I understand correctly, good programming implies
that a pointer must either be NULL or must contain a known
value, returned by malloc() and co.

And if I do want to manipulate the lvalue, it is better to make a
copy of the original pointer and deal with it. The lvalue must also
be unchanged (i.e. the one that malloc() returned), when the pointer
is passed to free().

Are the above assumptions correct?

Is even using the address of operator on an uninitialised pointer
undefined?

Thanks all.

Dec 5 '05 #10
santosh wrote:
Is even using the address of operator on an uninitialised pointer
undefined?


No.
The address of an object
does not depend on the value of the object.
Accessing the value of an uninitialised object,
is where the problems come from.

Likewise, the identifier of an uninitialised object
can be a valid operand of the sizeof operator.

--
pete
Dec 5 '05 #11
santosh wrote:

Hi,

If I call free() with a uninitialised pointer, will the program
state become undefined, or will free() return harmlessly?
Even if passing an invalid pointer to free() were permitted, imagine
what would happen if this uninitialized pointer just happened to have
the same value as a previously malloc'ed buffer. That alone should
be enough to understand why this must be undefined behavior.
Incidentally, is there a way in Standard C to determine
weather a pointer points to a valid block of allocated
memory?


No. I suppose you could put wrappers around malloc/calloc/recalloc/free
which tracks all allocated buffers, and then supply a function to check
if a pointer is in the list. This would, of course, only keep track of
your memory allocations, and not anything done within any library calls.

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody/at\spamcop.net | www.fptech.com | #include <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>

Dec 5 '05 #12
Jordan Abel wrote:
On 2005-12-04, Artie Gold <ar*******@austin.rr.com> wrote:
Emmanuel Delahaye wrote:
santosh a écrit :
Hi,

If I call free() with a uninitialised pointer, will the program
state become undefined, or will free() return harmlessly?
Undefined behaviour. A serious bug. Don't do that. Never.
Incidentally, is there a way in Standard C to determine
weather a pointer points to a valid block of allocated
memory?
Make it point to NULL by default or once free() has been performed. I
recommend this construction :

free(p), p = NULL;

It makes it easy to test, and it happens that free (NULL) is defined and
harmless.


Unfortunately, there are cases where doing so will mask a logic error
wherein otherwise a pointer would be free()-ed twice. So be careful.

it'll mask it or solve it? setting it to null guarantees that it won't
be freed twice, so this is hardly a "mask" - it actually changes the
logic to prevent the error


Perhaps.

It *will* avoid the UB -- but why, outside of very specific situations
(where the programmer knows *exactly* what he/she is doing) would one
free() the memory associated with a pointer more than once? And could it
be a case of mistakenly free()-ing the *wrong* pointer, introducing a
memory leak?

Too often, such constructions are used more as a band-aid than as a well
considered design decision (as it might be in the case of cleanup code
after failed resource acquisition, for example).

Just my .02.

HTH,
--ag
--
Artie Gold -- Austin, Texas
http://goldsays.blogspot.com
http://www.cafepress.com/goldsays
"If you have nothing to hide, you're not trying!"
Dec 5 '05 #13
"santosh" <sa*********@gmail.com> writes:
Keith Thompson wrote:
"santosh" <sa*********@gmail.com> writes:
> If I call free() with a uninitialised pointer, will the program
> state become undefined, or will free() return harmlessly?


This is, of course undefined behavior, but not because of the call to
free(). Any attempt to evaluate an uninitialized pointer variable
invokes undefined behavior. For example:

int *ptr; /* uninitialized */
if (ptr == NULL) ...; /* undefined behavior */

Realistically, the call to free() is more likely to cause something
bad to happen than the evaluation of the argument.


Thank you all for your clear replies.

To sum up, if I understand correctly, good programming implies
that a pointer must either be NULL or must contain a known
value, returned by malloc() and co.


A pointer can also contain the address of a declared object. If
you're not careful, this can cause similar problems if the object
ceases to exist before the pointer does. For example:

int *func(void)
{
int local_var;
return &local_var;
}

local_var ceases to exist when func() returns, but the caller now has
a pointer to this nonexistent object. If the caller attempts to use
this pointer value, it will invoke undefined behavior.

If you need to do this kind of thing, there are several workarounds.
You can declare local_var as static (which means every call to func()
will return the same address), or you can allocate the space with
malloc() (which means it's up to the caller to free() it), or you can
pass a pointer *into* the function and let the function assign a value
to the pointed-to object (which means the caller has to know -- or
guess -- how much space to allocate). This isn't likely to be an
issue for a pointer to int, but it's common when you want your
function to return an array, such as a string.

--
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.
Dec 5 '05 #14

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

Similar topics

2
by: John J | last post by:
I have written the following overload of operator << as a display function. In the code I unsuccessfully try and call a function within another class(<< "Race : " << r->Show () << endl). The Show...
7
by: Ramprasad A Padmanabhan | last post by:
Hello all, If I assign one pointer to another , I had assumed I can call them interchangably. I can explain by the example below. I am doing a malloc to char* a which is the same as char* b....
40
by: boris | last post by:
Hi! I'm seeking some answers about what seems to be a memory leak. I have a loop that looks much like this: double *largeArray = (double*) calloc(); for (...) { printf("iteration #...\n");...
19
by: Ross A. Finlayson | last post by:
Hi, I hope you can help me understand the varargs facility. Say I am programming in ISO C including stdarg.h and I declare a function as so: void log_printf(const char* logfilename, const...
86
by: Walter Roberson | last post by:
If realloc() finds it necessary to move the memory block, then does it free() the previously allocated block? The C89 standard has some reference to undefined behaviour if one realloc()'s memory...
6
by: I_have_nothing | last post by:
Hi! I am new in C. I try to use dynamical allocation fuction malloc( ) and realloc( ). I found something strange. After several calling realloc( ), the malloc( ) will give me a Segmentation...
7
by: Jack | last post by:
how does free know how much of memory to release if I say free(ptr)? Thanks.
1
by: philip123 | last post by:
I have a base class static character pointer d, which is called by 3 members in derived class in the following fashion BaseClass::d = strdup(x); //x is a character pointer whose value changes...
10
by: SQACPP | last post by:
Hi, I try to figure out how to use Callback procedure in a C++ form project The following code *work* perfectly on a console project #include "Windows.h" BOOL CALLBACK...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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
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,...
0
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...

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.