473,698 Members | 1,921 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

what will happen after i use free()???

i come from china,and i'm sorry that my english is very poor.

now i'm studing data structure and i met some problem about c language.

could you tell me what will happen after i use free()? i mean once i
use free() on a pointer,what will the pointer points to ?

for example:

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

void main()

{

int *p;
if(!p) printf("good");
else printf("fail");
p=(int *)malloc(100);
if(p) printf("\n\ngoo d");
else printf("\n\nfai l");

free(p);
if(!p) printf("\n\ngoo d");
else printf("\n\nfai l");

*p=100;
printf("\n\n%d" ,*p);
}

the result is:

fail

good

fail

100

why?

Mar 16 '06 #1
67 3775
ne********@gmai l.com wrote:
i come from china,and i'm sorry that my english is very poor.

now i'm studing data structure and i met some problem about c language.

could you tell me what will happen after i use free()? i mean once i
use free() on a pointer,what will the pointer points to ?

for example:

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

void main() main() returns int
{

int *p;
if(!p) printf("good"); Undefined behavior, the pointer has not been initialized. else printf("fail");
p=(int *)malloc(100); Do not cast the return value of malloc(). It is unnecessary and can
(though, in this case you have included the proper header) hide errors. if(p) printf("\n\ngoo d");
else printf("\n\nfai l");

free(p);
if(!p) printf("\n\ngoo d"); Undefined behavior. You can't even *look* at the value of a pointer (not
to mention dereference it) after it has been free()-ed. else printf("\n\nfai l");

*p=100; ...and now you've gone and dereferenced it... printf("\n\n%d" ,*p);
}

the result is:

fail
Undefined behavior means *anything* can happen. In this case the
`garbage' value of the pointer happened to be non-null.
good
You successfully allocated memory
fail
See above (undefined behavior).
100
Similarly.


HTH,
--ag
--
Artie Gold -- Austin, Texas
http://goldsays.blogspot.com
"You can't KISS* unless you MISS**"
[*-Keep it simple, stupid. **-Make it simple, stupid.]
Mar 16 '06 #2
neilcan...@gmai l.com wrote:
i come from china,and i'm sorry that my english is very poor.

now i'm studing data structure and i met some problem about c language.

could you tell me what will happen after i use free()? i mean once i
use free() on a pointer,what will the pointer points to ?

for example:

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

void main()
main returns int:

int main (void)

See:
http://www.c-faq.com/ansi/voidmain.html
http://www.c-faq.com/ansi/maindecl.html
http://www.c-faq.com/ansi/voidmainbooks.html
{

int *p;
if(!p) printf("good");
else printf("fail");
At this point p has not been initialized so it's value is indeterminate
and dereferencing the pointer will result in undefined behavior. In
fact, attempting to access it's value is also undefined behavior which
you have invoked in your if statement.
p=(int *)malloc(100);
Don't cast the return value of malloc.
See:
http://www.c-faq.com/malloc/mallocnocast.html

You should check the return value of malloc as it will return a null
pointer on failure.
if(p) printf("\n\ngoo d");
else printf("\n\nfai l");

free(p);
if(!p) printf("\n\ngoo d");
else printf("\n\nfai l");
Dereferencing a free'd pointer is undefined behavior, technically any
use of such a pointer, aside from assigning a new value to p, is
undefined behavior including the test in your if statement. The value
of p is not set to NULL after free is called.
See:
http://www.c-faq.com/malloc/ptrafterfree.html
*p=100;
Undefined behavior.
See:
http://www.c-faq.com/malloc/useafterfree.html
http://www.c-faq.com/malloc/ptrafterfree.html
printf("\n\n%d" ,*p);
}

the result is:

fail
Because automatic variables, including pointers, do not initialize
themselves and can contain any value, apparently that value wasn't 0 in
this case.
good
Because malloc returned a non-null value indicating success.
fail
Because free'd pointers aren't set to NULL.
100


Undefined behavior so anything can happen. In some implementations
attempting to access memory that has been free'd will result in program
termination or worse. Other implementations may not actually release
the memory but mark it as available for future calls to malloc in which
case it may be possible to continue to use the memory successfully but
it would be quite unwise to do so and is still undefined behavior.

Robert Gamble

Mar 16 '06 #3
my textbook is <the c programming language> by Kernighan and Ritchie.so
when i read your answer i felt astonished!!

first , i think in that book ,main can return void, but you told me it
was wrong!!

second ,i that book , malloc() is casted,cuz malloc() returns void.

the third is that thank you for teaching me the knowledge about free().
from now on i will never handle a pointer after it's free()ed. thank
you!

Mar 16 '06 #4
On Thursday 16 March 2006 08:13, Thunderbird opined (in
<11************ **********@i40g 2000cwc.googleg roups.com>):
my textbook is <the c programming language> by Kernighan and
Ritchie.so when i read your answer i felt astonished!!
Provide context! Read: <http://cfaj.freeshell. org/google/>.
first , i think in that book ,main can return void, but you told me it
was wrong!!

second ,i that book , malloc() is casted,cuz malloc() returns void.


I think you should get the Second Edition of the above title...

(I can't check all your claims now, as my K&R2 copy is in the office --
I should be there as well, but hey, it's a gray day out there...).

--
BR, Vladimir

Good night, Mrs. Calabash, wherever you are.

Mar 16 '06 #5
Thunderbird said:
my textbook is <the c programming language> by Kernighan and Ritchie.so
when i read your answer i felt astonished!!

first , i think in that book ,main can return void, but you told me it
was wrong!!
Page reference, please. (Don't spend forever trying to find it, though. K&R
does not in fact have any programs in it that abuse main's return type as
you suggest.)
second ,i that book , malloc() is casted,cuz malloc() returns void.
No, malloc returns void *, not void; and it requires no cast in C. K&R, for
some strange reason, decided to test their code using a C++ compiler. In
C++, the cast is required. In C, it is not. (But in C++, you almost
certainly won't be using malloc anyway.)
the third is that thank you for teaching me the knowledge about free().
from now on i will never handle a pointer after it's free()ed. thank
you!


free(p);
p = NULL;

is okay, though. (And wise, in most cases.)
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Mar 16 '06 #6
Thunderbird wrote:

my textbook is <the c programming language> by Kernighan and
Ritchie.so when i read your answer i felt astonished!!

first , i think in that book ,main can return void, but you told
me it was wrong!!

second ,i that book , malloc() is casted,cuz malloc() returns
void.


Look up the published errata from dmr for the book. All those
things are covered.

--
"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." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
Mar 16 '06 #7
On 2006-03-16, Vladimir S. Oka <no****@btopenw orld.com> wrote:
On Thursday 16 March 2006 08:13, Thunderbird opined (in
<11************ **********@i40g 2000cwc.googleg roups.com>):
my textbook is <the c programming language> by Kernighan and
Ritchie.so when i read your answer i felt astonished!!


Provide context! Read: <http://cfaj.freeshell. org/google/>.
first , i think in that book ,main can return void, but you told me it
was wrong!!

second ,i that book , malloc() is casted,cuz malloc() returns void.


I think you should get the Second Edition of the above title...

(I can't check all your claims now, as my K&R2 copy is in the office --
I should be there as well, but hey, it's a gray day out there...).


K&R2 does cast malloc in some places. Main never returns void, but
sometimes it doesn't return a value.
Mar 16 '06 #8
Richard Heathfield 写道:

Page reference, please. (Don't spend forever trying to find it, though. K&R
does not in fact have any programs in it that abuse main's return type as
free(p);
p = NULL;

is okay, though. (And wise, in most cases.)

thank u very much.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)


Mar 16 '06 #9
Hi,

This is a concept called Dangling pointer. Once u free the pointer
pointer does't point any memory location. So, the program gives a
problem. In real life after int *p; now person born then can u offer
some food correct, then he will work fine. Once that person died means
free(p) free of pointer. I can't offer any food to him correct. But, u
are offering *p=100. some food. Think, how it is possible in general
life. The same thing here. If u want once again allocate memory and use
it.
I think by this u will got. If, u want more and detailed explanation
conatct. Always welcome.

Regards,
Ravi Nakidi,
S/w Enginner.

Mar 17 '06 #10

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

Similar topics

220
19035
by: Brandon J. Van Every | last post by:
What's better about Ruby than Python? I'm sure there's something. What is it? This is not a troll. I'm language shopping and I want people's answers. I don't know beans about Ruby or have any preconceived ideas about it. I have noticed, however, that every programmer I talk to who's aware of Python is also talking about Ruby. So it seems that Ruby has the potential to compete with and displace Python. I'm curious on what basis it...
92
6475
by: Reed L. O'Brien | last post by:
I see rotor was removed for 2.4 and the docs say use an AES module provided separately... Is there a standard module that works alike or an AES module that works alike but with better encryption? cheers, reed
121
10079
by: typingcat | last post by:
First of all, I'm an Asian and I need to input Japanese, Korean and so on. I've tried many PHP IDEs today, but almost non of them supported Unicode (UTF-8) file. I've found that the only Unicode support IDEs are DreamWeaver 8 and Zend PHP Studio. DreamWeaver provides full support for Unicode. However, DreamWeaver is a web editor rather than a PHP IDE. It only supports basic IntelliSense (or code completion) and doesn't have anything...
53
4069
by: Deniz Bahar | last post by:
I know the basic definition of a sequence point (point where all side effects guaranteed to be finished), but I am confused about this statement: "Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored." Can someone give me examples of expressions that "barely"...
18
2252
by: Ramasubbu Ramasubramanian XR (AS/EAB) | last post by:
What is memory leakage, could any one explain with sample code
13
5040
by: Jason Huang | last post by:
Hi, Would someone explain the following coding more detail for me? What's the ( ) for? CurrentText = (TextBox)e.Item.Cells.Controls; Thanks. Jason
63
4768
by: Jake Barnes | last post by:
In the course of my research I stumbled upon this article by Alex Russel and Tim Scarfe: http://www.developer-x.com/content/innerhtml/default.html The case is made that innerHTML should never be used. I'm wondering, If I wanted all the content of BODY as a string, how else could I get except through innerHTML?
5
2841
by: Tom | last post by:
I have a function that restricts access to a page to logged in users. When a user who isn't logged in goes to the page, it will dynamically generate a login form. I'm trying to use it in conjunction with the free shared SSL certificate offered by my host. To use SSL, you would change a URL like this http://mydomain.com/page.php
14
1886
by: cat_dog_ass | last post by:
....Microsoft ports the .NET framework to other operating systems? Will the only advantage that Java has over .NET be lost? I've been a Java programmer and will be shifting to .NET soon. Is this a wise choice? Is the learning curve for C# a lot flatter than Java?
0
8671
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9152
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...
1
8887
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8856
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
7709
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 projectplanning, coding, testing, and deploymentwithout 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
6515
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
5858
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
4360
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...
2
2321
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.