473,721 Members | 2,133 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
67 3783
santosh wrote:
Thunderbird wrote:
.... snip ...
is there any difference in standard c between "p=(char
*)malloc(1000)" and "p=malloc(1000) "?


p = malloc( 1000 * sizeof (char) ) is a better form than both the
above.


No it isn't. sizeof(char) is always 1. If you do want to make
things track the type of p properly, write:

p = malloc(1000 * sizeof *p);

--
"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 18 '06 #21
CBFalconer wrote:
santosh wrote:
Thunderbird wrote:

... snip ...
is there any difference in standard c between "p=(char
*)malloc(1000)" and "p=malloc(1000) "?


p = malloc( 1000 * sizeof (char) ) is a better form than both the
above.


No it isn't. sizeof(char) is always 1. If you do want to make
things track the type of p properly, write:

p = malloc(1000 * sizeof *p);


Thanks for the correction.

Mar 18 '06 #22
On Fri, 17 Mar 2006 18:44:03 UTC, "Vladimir S. Oka"
<no****@btopenw orld.com> wrote:
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.)


now there is another thing i wanna know.should i cast malloc when i
call malloc() in standard c?


Yes, since otherwise you won't be alerted by the compiler if you fail to
#include <stdlib.h>.


Liar! Never ever cast the return value of a function returning void* -
except you likes to land in the world of undefined behavior.
is there any difference in standard c between "p=(char
*)malloc(1000)" and "p=malloc(1000) "?


Functionally, no, but see previous comment (i.e. not casting is not
required, but good sense).


Liar! There IS a mayor difference (<any cast>) malloc() results in
undefined behavor, p=malloc() is the only secure call allowed in C.

There are implementations using different places for different return
types, so casting results in getting some unspecified value converted
to some undefined value -> undefined behavior.

There is under absolutely no circomstance a need for a cast of (void*)
to anything else.

True, some diagnostic may show not clearly what you expects but what
the compiler sees. casting is in absolute way never ever a solution to
get an diagnostic away.

You should cast only if you are absoltely knows what <ou're doing.
cast only to get a diagnostic away is always and under any
circumstance lying to the compiler and the compiler will revange for
that lie in any way it likes.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Mar 19 '06 #23
Herbert Rosenau opined:
On Fri, 17 Mar 2006 18:44:03 UTC, "Vladimir S. Oka"
<no****@btopenw orld.com> wrote:
>> 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.)
>
> now there is another thing i wanna know.should i cast malloc when
> i call malloc() in standard c?
Yes, since otherwise you won't be alerted by the compiler if you
fail to
#include <stdlib.h>.


Liar! Never ever cast the return value of a function returning void*
- except you likes to land in the world of undefined behavior.


I do not particularly care being called a liar, especially followed by
an exclamation mark, but I'll give you a benefit of a doubt...

Yes, I have mistyped "yes" for "no", which Richard kindly pointed out
in elsethread, and I have acknowledged that.

I still don't think casting the result off `malloc()` results in
undefined behaviour. Why would it? Remember, we were talking about
casting to a different /pointer/ type, not just /any/ type.
> is there any difference in standard c between "p=(char
> *)malloc(1000)" and "p=malloc(1000) "?


Functionally, no, but see previous comment (i.e. not casting is not
required, but good sense).


Liar!


Now you're skating on thin ice with your choice of words!
There IS a mayor difference (<any cast>) malloc() results in
undefined behavor
Care to elaborate on how exactly my answer to the OP's question is
factually wrong. I advise you again to read the OP, where casting from
`void *` to `char *` (or some other pointer type) is discussed, not
casting to, say, `double`.
p=malloc() is the only secure call allowed in C.
I submit that:

#include <stdio.h>

...

puts("Hello, world!");

is safe as well.
There are implementations using different places for different return
types,
Maybe, but how does this relate to:
so casting results in getting some unspecified value converted
to some undefined value -> undefined behavior.
I'm a bit confused by this, but I think I see where you're aiming at.
There is under absolutely no circomstance a need for a cast of
(void*) to anything else.
We seem to agree on this, making me wonder what your post was really
about...
True, some diagnostic may show not clearly what you expects but what
the compiler sees. casting is in absolute way never ever a solution
to get an diagnostic away.
Yes, that was my reply to the OP as well (in slightly less strong
terms).
You should cast only if you are absoltely knows what <ou're doing.
cast only to get a diagnostic away is always and under any
circumstance lying to the compiler and the compiler will revange for
that lie in any way it likes.


Again, yes, but IMHO beside the point.

--
BR, Vladimir

It's possible that the whole purpose of your life is to serve
as a warning to others.

Mar 19 '06 #24
"Herbert Rosenau" <os****@pc-rosenau.de> wrote in message
news:wm******** *************** ****@URANUS1.DV-ROSENAU.DE...
On Fri, 17 Mar 2006 18:44:03 UTC, "Vladimir S. Oka"
<no****@btopenw orld.com> wrote:
>> 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.)
>
> now there is another thing i wanna know.should i cast malloc when i
> call malloc() in standard c?


Yes, since otherwise you won't be alerted by the compiler if you fail to
#include <stdlib.h>.


Liar! Never ever cast the return value of a function returning void* -
except you likes to land in the world of undefined behavior.


Why do you even *imagine* that someone would lie about a thing
so unimportant as this? Besides, it's extremely bad manners to
accuse someone of lying in this forum. Besides, you're wrong.
> is there any difference in standard c between "p=(char
> *)malloc(1000)" and "p=malloc(1000) "?


Functionally, no, but see previous comment (i.e. not casting is not
required, but good sense).


Liar! There IS a mayor difference (<any cast>) malloc() results in
undefined behavor, p=malloc() is the only secure call allowed in C.


You just did it again. And you were factually wrong again. Couth up.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Mar 19 '06 #25
On Sun, 19 Mar 2006 08:54:20 +0000 (UTC), in comp.lang.c , "Herbert
Rosenau" <os****@pc-rosenau.de> wrote:
(<any cast>) malloc() results in
undefined behavor, p=malloc() is the only secure call allowed in C.
Rubbish. Inserting a cast before malloc is not needed, but doesn't
result in UB.
There is under absolutely no circomstance a need for a cast of (void*)
to anything else.


variadic functions?
Mark McIntyre
--
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Mar 19 '06 #26
On Sun, 19 Mar 2006 11:27:39 UTC, Mark McIntyre
<ma**********@s pamcop.net> wrote:
On Sun, 19 Mar 2006 08:54:20 +0000 (UTC), in comp.lang.c , "Herbert
Rosenau" <os****@pc-rosenau.de> wrote:
(<any cast>) malloc() results in
undefined behavor, p=malloc() is the only secure call allowed in C.


Rubbish. Inserting a cast before malloc is not needed, but doesn't
result in UB.


You should program under an environment that would use for return
valuses of different types different locations and then use casting on
functions returning other than int, forgetting to #include stdlib you
gets undefined behavior - find then all that will cost you more time
as to write one million lines of conforming code. It is m ore than
important only using a cast when you 10000000% exactly sure that you
knows what you does or you will deliver extremly bad programs who may
cost not only damage but human live - only because you are too dumb to
see that making casts where you must lie to the compiler only to get
an diagnosting away instead to follow the rules tho says never use a
cast when you're not clearly and absolutely sure that it isd needed to
become what you would but not only to get diagnostics away.
There is under absolutely no circomstance a need for a cast of (void*)
to anything else.


variadic functions?
Mark McIntyre

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Mar 19 '06 #27
Herbert Rosenau opined:
On Sun, 19 Mar 2006 11:27:39 UTC, Mark McIntyre
<ma**********@s pamcop.net> wrote:
On Sun, 19 Mar 2006 08:54:20 +0000 (UTC), in comp.lang.c , "Herbert
Rosenau" <os****@pc-rosenau.de> wrote:
> (<any cast>) malloc() results in
>undefined behavor, p=malloc() is the only secure call allowed in C.
Rubbish. Inserting a cast before malloc is not needed, but doesn't
result in UB.


You should program under an environment that would use for return
valuses of different types different locations and then use casting
on functions returning other than int,


Again, can you please elaborate /why/ you think this matters (physical
storage of return values)?
forgetting to #include stdlib you gets undefined behavior
And why it would lead to this?
- find then all that will cost you more
time as to write one million lines of conforming code.
Are you now proposing writing non-conforming code?
It is m ore
than important only using a cast when you 10000000% exactly sure that
you knows what you does or you will deliver extremly bad programs
I can agree with this.
who
may cost not only damage but human live - only because you are too
dumb to see that making casts where you must lie to the compiler only
to get an diagnosting away instead to follow the rules tho says never
use a cast when you're not clearly and absolutely sure that it isd
needed to become what you would but not only to get diagnostics away.


Apart from calling people names again, you also forgot to breathe. Your
posts are increasingly resembling any of the dozens of definitions of
flaming. You risk becoming a troll...

--
BR, Vladimir

Do not overtax your powers.

Mar 19 '06 #28
On Sun, 19 Mar 2006 12:33:52 +0000 (UTC), in comp.lang.c , "Herbert
Rosenau" <os****@pc-rosenau.de> wrote:
On Sun, 19 Mar 2006 11:27:39 UTC, Mark McIntyre
<ma**********@ spamcop.net> wrote:
On Sun, 19 Mar 2006 08:54:20 +0000 (UTC), in comp.lang.c , "Herbert
Rosenau" <os****@pc-rosenau.de> wrote:
> (<any cast>) malloc() results in
>undefined behavor, p=malloc() is the only secure call allowed in C.
Rubbish. Inserting a cast before malloc is not needed, but doesn't
result in UB.


You should program under an environment that would use for return
valuses of different types different locations


I've programmed for these, they're a classic reason why you must
include stdlib.h. Its nothing to do with casting tho.
and then use casting on
functions returning other than int, forgetting to #include stdlib you
gets undefined behavior


This has nothing to do with casting malloc, its entirely to do with
returing ints and pointers in different registers.

The cast masks the error, it doesn't cause it. Don't let yourself get
confused by cause and effect.
>There is under absolutely no circomstance a need for a cast of (void*)
>to anything else.


At the risk of repeating myself, variadic functions?
Mark McIntyre
--
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Mar 19 '06 #29
On Sun, 19 Mar 2006 13:00:22 +0000 (UTC), in comp.lang.c , "Vladimir
S. Oka" <no****@btopenw orld.com> wrote:
Herbert Rosenau opined:
You should program under an environment that would use for return
valuses of different types different locations and then use casting
on functions returning other than int,


Again, can you please elaborate /why/ you think this matters (physical
storage of return values)?


On the h/w in question, pointers are returned (say) in the A1register,
and ints in the B1 register.

Failure to include stdlib.h causes the compiler to think malloc
returns an int, and emit code to read from B1. The real pointer is of
course in A1, so any attempt to write through the pointer will cause a
crash.
forgetting to #include stdlib you gets undefined behavior


And why it would lead to this?


See above. The compiler does of course complain about the incompatible
returns, and novice or C++ programmers insert a cast to silence it.

I agree with you tho, the UB is nothing to do with the cast, its to do
with not properly declaring malloc. The same would apply to any
function returning a pointer on this h/w. If stdlib had been included,
the code, with or without cast, would have been well defined.
Mark McIntyre
--
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Mar 19 '06 #30

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

Similar topics

220
19078
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
6493
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
10111
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
4078
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
2261
by: Ramasubbu Ramasubramanian XR (AS/EAB) | last post by:
What is memory leakage, could any one explain with sample code
13
5048
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
4784
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
8840
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
9367
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
9131
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
9064
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
8007
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 project—planning, coding, testing, and deployment—without 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...
0
5981
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
4484
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
2576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2130
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.