473,756 Members | 2,703 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 3795
On Sun, 19 Mar 2006 14:49:17 +0100, in comp.lang.c , "Richard G.
Riley" <rg****@gmail.c om> wrote:
in this case I would
ask you HOW you intend malloc to return different memory banks for
different types considering you cant tell malloc what it is malloc'ing
for.


You might want to read up on how early Motorola chips worked, before
sounding off...

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 #41
In article <jq************ *************** *****@4ax.com>,
Mark McIntyre <ma**********@s pamcop.net> wrote:
in this case I would
ask you HOW you intend malloc to return different memory banks for
different types considering you cant tell malloc what it is malloc'ing
for.
You might want to read up on how early Motorola chips worked, before
sounding off...


Yes, but that relates to different functions (returning pointers or
integers) rather than - as Riley misinterpreted - a function returning
memory to be used for different types. A function of given return
type always returned in the same register.

(Has so much time really passed that 68000s are "early Motorola
chips"?)

-- Richard
Mar 19 '06 #42
Jordan Abel <ra*******@gmai l.com> writes:
On 2006-03-19, Keith Thompson <ks***@mib.or g> wrote:

[...]
For example, the following:
[snip]
is perfectly valid; the cast is unnecessary, but harmless. (The cast
is harmful if it converts the result to the wrong type, or if it masks
a failure to include <stdlib.h>, or if it masks a failure to use a C
compiler rather than a C++ compiler.


Though, use of a C++ compiler could be by design. Didn't K&R verify
their code for the second edition using a C++ compiler, since there
weren't any 'proto-ansi' C compilers in existence yet?


Yes, that's true, and I explicitly acknowledged in a paragraph that
you snipped that there can be valid reasons to compile C code with a
C++ compiler. (The use of a C++ compiler, I think is, why the
examples in K&R2 cast the result of malloc(); it's corrected in the
errata.)

--
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.
Mar 19 '06 #43
Mark McIntyre <ma**********@s pamcop.net> writes:
On Sun, 19 Mar 2006 14:49:17 +0100, in comp.lang.c , "Richard G.
Riley" <rg****@gmail.c om> wrote:
in this case I would
ask you HOW you intend malloc to return different memory banks for
different types considering you cant tell malloc what it is malloc'ing
for.


You might want to read up on how early Motorola chips worked, before
sounding off...


Richard's error, I think, was in assuming we were talking about
different calls to malloc() returning their results in different
registers. Reading about the M68K wouldn't clear that up.

--
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.
Mar 19 '06 #44
On Sun, 19 Mar 2006 13:00:22 UTC, "Vladimir S. Oka"
<no****@btopenw orld.com> wrote:
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)?


C Standard C makes absolutely no assumption how an implementation
should handle such things as returning values from functions. So each
implementation does it in a way best resolved by the underlying
hardware. Intel on on that aspect one of the littlest market ever seen
even as M$ means that they have the mayority.

So there are implementations around where void* or char* will occupy
56 bits while int is only 48 bits. They have special registers for
storing pinters in, other to stor floatingpoint values and another to
store int pointers, having other instructions addressing pointers
other ones addressing floating point values, other for floatingpoint
and so on.

Getting an exception on addressing a pointer in int registers creates
an exception.

A void* can not been interpreted as int - whereas C defines that any
undefined function returns int. So casting that value requires some
special mashine instructs and will fail miserably becaus the 56 bits
returned by malloc gets lost completely while an random bitpattern
gets used for converting that to a pointer.
forgetting to #include stdlib you gets undefined behavior


And why it would lead to this?


Because the differences between void* and int are significant and may
occre in something but not what you means you get.
- 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?


No, here we speak only about strictly conforming code.
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...

That doesn't disturb me. Only trolls will name others who tries to
teach a troll.

Here you'll see nearly dayly an idiot who means that casting to hide
diagnostics is ok. True, many peoples coming here have learned that by
reading defektive books, broken code from idiots, so I try to help
them to get it right whenever I have free time to do so.

As this thread is running for more than a week now I get allergic to
read again and again therin casting results returning from functions
like malloc is ok.

It looks like there is a need to drum into somebody that casting is
almost the wrongest method to resolve a problem.

Use cast only if you are absolutely sure that yor really needs the
cast and after you have checked and rechecked again and again that you
really knows what you does and not on the way to lie to the compiler.
lie to the compiler and it will get its dreadful revange.

Myself had learned that more than 20 years ago even on K&RII by
falling through cede inspections, failing on getting the results I
expected before I learned how to use casts right. There was no usenet
ready to learn from others.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Mar 19 '06 #45
On Sun, 19 Mar 2006 13:24:31 UTC, Mark McIntyre
<ma**********@s pamcop.net> wrote:
>There is under absolutely no circomstance a need for a cast of (void*)
>to anything else.


At the risk of repeating myself, variadic functions?


I've had in 20 years of experience in C not a single time the need to
cast a void* to an variadic function (not even printf) because the
caller would never know what real type is sitting behind the void* -
but the callee knows that he gets a void* and will either been able to
use the data or is only a forwarder to a function that knows about the
real data.

void* is a nice method to hide information to data that is handled in
specific parts of the program but needs stored external of them
because the livetime of the data requires that. Information hiding
makes maintenance of big programs more secure.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Mar 19 '06 #46
On Sun, 19 Mar 2006 13:49:17 UTC, "Richard G. Riley"
<rg****@gmail.c om> wrote:
This was a discussion of some merriment a while ago. Sometimes things
are made a little too clever for their own good : in this case I would
ask you HOW you intend malloc to return different memory banks for
different types considering you cant tell malloc what it is malloc'ing
for.


Really? Why does you need to tell malloc() which different type you
needs memory for?

Yes, there is a possibility to help malloc in organising its heap
better:
- a high frequency of dynamic to allocate memory in high
different size
- extremely high usage of dynamic memory because the mass
of data is nearly on the address space the underlying
OS is willing to give an single application.

Solution: Write your own replacement of malloc that maintains multiple
lists of different size groups. Anyway, malloc() has never a need to
know what type of date ist should give a chunk of memory for and so it
will return simply a void* pointing to the 1. byte of the memory it
has reserved in the given size.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Mar 19 '06 #47
On Sun, 19 Mar 2006 15:12:17 UTC, ri*****@cogsci. ed.ac.uk (Richard
Tobin) wrote:
In article <wm************ *************** @URANUS1.DV-ROSENAU.DE>,
Herbert Rosenau <os****@pc-rosenau.de> wrote:
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


Using malloc() without a declaration will cause undefined behaviour,
but casting the result of malloc() will not. The main problem with
casting it is that it may disguise the fact that it's not declared.


You're in error. Who guarantees that your compiler will give you
exactly the same bits in the same meaning that malloc returns? There
are many reasons why the cast of the result of the undecleard malloc
give you something that is absolutely independant from the value
malloc has given back to the caller -> undefined behavior is
guaranteed.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Mar 19 '06 #48
On Sun, 19 Mar 2006 16:44:16 UTC, Keith Thompson <ks***@mib.or g>
wrote:
"Herbert Rosenau" <os****@pc-rosenau.de> writes:
On Fri, 17 Mar 2006 18:44:03 UTC, "Vladimir S. Oka"
<no****@btopenw orld.com> wrote: [...]
> 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.


Vladimir accidentally typed "Yes" when he clearly meant "No". This
has already been pointed out and acknowledged. Possibly you didn't
see that, but it should have been obvious from the rest of what he
wrote.


I don't read always immediately all messages my server serves me and
sometimes my server likes to give me not all messages already written
and currently on some server prior it on the way to it. So when I read
a thread I can only read what is already inside my client. That means
I read a message and decide to answer or not before I switch to the
next one.
> 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.


Nonsense. Calling malloc() with no prototype in scope causes
undefined behavior (at least in C90). Applying a correct cast does
not make the behavior any more or less defined.

For example, the following:

#include <stdlib.h>
int main(void)
{
int *ptr = (int*)malloc(si zeof(int));
return 0;
}

is perfectly valid; the cast is unnecessary, but harmless. (The cast
is harmful if it converts the result to the wrong type, or if it masks
a failure to include <stdlib.h>, or if it masks a failure to use a C
compiler rather than a C++ compiler. All these can be easy mistakes
to make, which is why we strongly discourage casting the result of
malloc().)


The cast is superflous and NOT harmell because it will hide any
diagnostic when the #include gets removed. Don't tell me that would
never occure. Such mistakes are easy done on the next review of the
code.
And a very few people have valid reasons to write code that will
compile as both C and C++; for them, the cast (done carefully) is
mandatory.


There is no reason to send a call of malloc() through C++ compiler.
With that argument you should require that the stdlib has to be
compilant to pascal, Algol, Fortran, LISP and other languages too.
--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Mar 19 '06 #49
On Sun, 19 Mar 2006 17:55:16 UTC, Jordan Abel <ra*******@gmai l.com>
wrote:
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.


Correct. If the cast masks an error message, the undefined behavior has
already happened.


No, the cast is to hide any diagnostic - it is still a lie to the
compiler.

--
Tschau/Bye
Herbert

Visit http://www.ecomstation.de the home of german eComStation
eComStation 1.2 Deutsch ist da!
Mar 19 '06 #50

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

Similar topics

220
19124
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
6513
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
10135
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
4088
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
2265
by: Ramasubbu Ramasubramanian XR (AS/EAB) | last post by:
What is memory leakage, could any one explain with sample code
13
5053
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
4792
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
2844
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
1893
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
9431
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
9255
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
9844
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
8688
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...
1
7226
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
6514
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
5119
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
5289
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3780
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.