473,714 Members | 2,500 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 3780
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
19061
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
6490
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
10107
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
4076
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
2260
by: Ramasubbu Ramasubramanian XR (AS/EAB) | last post by:
What is memory leakage, could any one explain with sample code
13
5045
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
4783
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
2843
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
1888
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
8801
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
8707
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
9174
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...
1
9074
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
9015
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
5947
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
4464
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
2520
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2110
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.