468,248 Members | 1,513 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,248 developers. It's quick & easy.

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\ngood");
else printf("\n\nfail");

free(p);
if(!p) printf("\n\ngood");
else printf("\n\nfail");

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

the result is:

fail

good

fail

100

why?

Mar 16 '06 #1
67 3310
ne********@gmail.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\ngood");
else printf("\n\nfail");

free(p);
if(!p) printf("\n\ngood"); 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\nfail");

*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...@gmail.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\ngood");
else printf("\n\nfail");

free(p);
if(!p) printf("\n\ngood");
else printf("\n\nfail");
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**********************@i40g2000cwc.googlegroups .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.com, 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/googlegroupsreply/>
Mar 16 '06 #7
On 2006-03-16, Vladimir S. Oka <no****@btopenworld.com> wrote:
On Thursday 16 March 2006 08:13, Thunderbird opined (in
<11**********************@i40g2000cwc.googlegroups .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
Ravi Nakidi wrote:
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.


How do you expect anyone to understand the above?
Also please quote whomever you're replying to.

Mar 17 '06 #11
Richard Heathfield wrote:

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.)
now i wanna know what main() returns? int? is it wrong when i
write"void main()"in my programme? or i must write "int main()" since
it is the only correct way?
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?

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

thank u

Mar 17 '06 #12
On Friday 17 March 2006 18:32, Thunderbird opined (in
<11*********************@p10g2000cwp.googlegroups. com>):
Richard Heathfield wrote:
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.)
now i wanna know what main() returns? int? is it wrong when i
write"void main()"in my programme? or i must write "int main()" since
it is the only correct way?


At the risk of being trolled (I'm not sure I like the tone)...

The C Standard allows only:

int main(void)
int main(int argc, char *argv[])

However, it also allows particular implementations to specify whatever
they want, _as_long_as_it's_documented_. So, if your C compiler's
documentation says so, you may as well use:

float main(double *x)

NB, using this will break your code if you want to recompile on a
different implementation (and none are required to support anything not
in C Standard).
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>.
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).

--
BR, Vladimir

Forgive, O Lord, my little jokes on Thee
And I'll forgive Thy great big one on me.
-- Robert Frost

Mar 17 '06 #13
Thunderbird wrote:
Richard Heathfield wrote:

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.)
now i wanna know what main() returns? int? is it wrong when i
write"void main()"in my programme? or i must write "int main()" since
it is the only correct way?


According to the C99 standard main() is required to return an int
value. The form 'void main()' is not correct though many cheap C books
seem to unaccountably prefer it.
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?


It's strongly preferable to *not* cast malloc()'s return value.
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.

Mar 17 '06 #14
Op 17 Mar 2006 10:44:15 -0800 schreef santosh:
Thunderbird wrote:
Richard Heathfield wrote:

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.)


now i wanna know what main() returns? int? is it wrong when i
write"void main()"in my programme? or i must write "int main()" since
it is the only correct way?


According to the C99 standard main() is required to return an int
value. The form 'void main()' is not correct though many cheap C books
seem to unaccountably prefer it.
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?


It's strongly preferable to *not* cast malloc()'s return value.
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.


Nonsense, sizeof (char) is always one in every conforming implementation
--
Groetjes, Coos
Mar 17 '06 #15
On Friday 17 March 2006 21:23, Coos Haak opined (in
<ct***************************@40tude.net>):
Op 17 Mar 2006 10:44:15 -0800 schreef santosh:
p = malloc( 1000 * sizeof (char) ) is a better form than both the
above.


Nonsense, sizeof (char) is always one in every conforming
implementation


Redundant, maybe. Nonsense, no.

IMHO, it's always better to spell out exactly what you mean. So, if
you're allocating memory for `char` -- say so. It will make your, or
maintainer's life much easier two years down the line.

--
BR, Vladimir

The herd instinct among economists makes sheep look like independent
thinkers.

Mar 17 '06 #16
Vladimir S. Oka said:
On Friday 17 March 2006 18:32, Thunderbird opined (in
<11*********************@p10g2000cwp.googlegroups. com>):
now there is another thing i wanna know.should i cast malloc when i
call malloc() in standard c?
Yes,


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


--
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 17 '06 #17
Vladimir S. Oka said:
On Friday 17 March 2006 21:23, Coos Haak opined (in
<ct***************************@40tude.net>):
Op 17 Mar 2006 10:44:15 -0800 schreef santosh:
p = malloc( 1000 * sizeof (char) ) is a better form than both the
above.


Nonsense, sizeof (char) is always one in every conforming
implementation


Redundant, maybe. Nonsense, no.

IMHO, it's always better to spell out exactly what you mean. So, if
you're allocating memory for `char` -- say so. It will make your, or
maintainer's life much easier two years down the line.


I disagree, since it creates a maintenance headache when you change to
wchar_t. Better:

p = malloc(1000 * sizeof *p);

--
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 17 '06 #18
On Friday 17 March 2006 21:36, Richard Heathfield opined (in
<dv**********@nwrdmz01.dmz.ncs.ea.ibs-infra.bt.com>):
Vladimir S. Oka said:
On Friday 17 March 2006 18:32, Thunderbird opined (in
<11*********************@p10g2000cwp.googlegroups. com>):
now there is another thing i wanna know.should i cast malloc when i
call malloc() in standard c?


Yes,


You mean no.


Yes, of course (I meant no). My head's still spinning from the OP. ;-)

--
BR, Vladimir

Oh, by the way, which one's Pink?
-- Pink Floyd

Mar 17 '06 #19
On Friday 17 March 2006 21:37, Richard Heathfield opined (in
<dv**********@nwrdmz01.dmz.ncs.ea.ibs-infra.bt.com>):
Vladimir S. Oka said:
On Friday 17 March 2006 21:23, Coos Haak opined (in
<ct***************************@40tude.net>):
Op 17 Mar 2006 10:44:15 -0800 schreef santosh:

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


IMHO, it's always better to spell out exactly what you mean. So, if
you're allocating memory for `char` -- say so. It will make your, or
maintainer's life much easier two years down the line.


I disagree, since it creates a maintenance headache when you change to
wchar_t. Better:

p = malloc(1000 * sizeof *p);


Agreed. I should've spent a minute more on my post. :-(

--
BR, Vladimir

People tend to make rules for others and exceptions for themselves.

Mar 17 '06 #20
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.com, 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/googlegroupsreply/>
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****@btopenworld.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****@btopenworld.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****@btopenworld.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**********@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 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**********@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 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****@btopenworld.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
On 2006-03-19, 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 and then use casting

on

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.
Mar 19 '06 #31
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.

-- Richard
Mar 19 '06 #32
"Richard G. Riley" <rg****@gmail.com> writes:
On 2006-03-19, 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 and then use casting

on

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.


malloc() returns a result of type void*. Presumably it always returns
that result in the same way, but it could return it in, say, an
address register. A function *other than malloc()* could return its
result in, say, a data register rather than an address register.
Calling malloc() with no visible prototype (at least in C90) causes
the compiler to assume that malloc() returns int, and therefore that
its result will be in a different register than the one malloc()
actually uses.

--
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.
Mar 19 '06 #33
"Herbert Rosenau" <os****@pc-rosenau.de> writes:
On Fri, 17 Mar 2006 18:44:03 UTC, "Vladimir S. Oka"
<no****@btopenworld.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.
> 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(sizeof(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().)

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.

However, I'm going to assume that this was an honest mistake on your
part. I'm going to resist the temptation to call you a liar, with or
without an exclamation point.

Conceivably this is a language problem. To be clear, by using the
word "liar", you are accusing Vladimir of deliberately, maliciously,
and knowingly making false statements. This is extraordinarily rude
on your part, as well as being wrong.

You owe Vladimir (and the rest of us) an apology.

--
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.
Mar 19 '06 #34
Herbert Rosenau wrote:
"Vladimir S. Oka" <no****@btopenworld.com> wrote:

.... snip ...

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.


You are apparently trying to take over Dan Pops place in the
pantheon of diplomatic c.l.c posters. Calling someone a liar is
not going to get you very far. This is possibly a language barrier
problem (which Dan never had). Maybe you meant to say "false" or
"not so" or even "I disagree" etc.

--
"If you want to post a followup via groups.google.com, 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/googlegroupsreply/>
Mar 19 '06 #35
On 2006-03-19, Vladimir S. Oka <no****@btopenworld.com> wrote:
Herbert Rosenau opined:
On Fri, 17 Mar 2006 18:44:03 UTC, "Vladimir S. Oka"
<no****@btopenworld.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.


Correct. If the cast masks an error message, the undefined behavior has
already happened.
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!


Your wording was awkward - it's easy to skim over the extra "not", and
think you said "casting is not required, but good sense". In combination
with the "yes" from before, it's even easier to miss.
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.


I think he meant the only secure call _to malloc_ :P
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.


"unspecified value" nothing - calling a function that returns void * as
if it were a function returning int is flat-out undefined behavior. Say
that a given implementation returns on the stack, and the extra space
overwritten by the [larger] void * overwrites something important, like
half of a return address.
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.

Mar 19 '06 #36
On 2006-03-19, 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 and then use casting on
functions returning other than int, forgetting to #include stdlib you
gets undefined behavior


The undefined behavior is not caused by the cast, and would happen
without it.

Also, people who can only think of an implementation using different
registers for pointers, or having larger pointers and so having half the
pointer chopped off, have no imagination. What if the register that's
used for returning pointers in functions that do so is supposed to be
saved by the callee in other functions, and was being used by the caller
for something important? If only part of the pointer representation fits
in the "int return register", where does the other half go? It has to go
somewhere, and since the caller isn't expecting anything in wherever
that somewhere is, serious problems could happen.
>There is under absolutely no circomstance a need for a cast of (void*)
>to anything else.


variadic functions?


That'd be more likely to need to be a cast TO void * than FROM void *.
Or a cast of a null pointer constant, which could just as easily be 0 as
(void*)0.
Mar 19 '06 #37
On 2006-03-19, Richard G. Riley <rg****@gmail.com> wrote:
On 2006-03-19, 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 and then use casting

on

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.


No... he's talking about the implementation of function calls using a
different location for return VALUES [i.e. the pointer or int itself] of
different types, not anything about the implementation of malloc.

(unless you're thinking of the floating-point-memory discussion. that
was fun. the implementation of struct layouts that someone came up with
was VERY convoluted)
Mar 19 '06 #38
On 2006-03-19, Keith Thompson <ks***@mib.org> wrote:
"Herbert Rosenau" <os****@pc-rosenau.de> writes:
On Fri, 17 Mar 2006 18:44:03 UTC, "Vladimir S. Oka"
<no****@btopenworld.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.
> 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(sizeof(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.


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?

"It's a subset of C++ now and will be a subset of C once C catches up",
basically.
Mar 19 '06 #39
In article <2v********************************@4ax.com>,
Mark McIntyre <ma**********@spamcop.net> wrote:
There is under absolutely no circomstance a need for a cast of (void*)
to anything else.
variadic functions?


Pedantically, there is never a *need* for a cast of void *, since you
could instead assign it to a variable of the right type and use that.
But there are plenty of cases where a cast is natural, such as in
simple comparison functions for qsort(), for example:

static int int_compare(const void *a, const void *b)
{
return *(int *)a - *(int *) b;
}

-- Richard
Mar 19 '06 #40
On Sun, 19 Mar 2006 14:49:17 +0100, in comp.lang.c , "Richard G.
Riley" <rg****@gmail.com> 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**********@spamcop.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*******@gmail.com> writes:
On 2006-03-19, Keith Thompson <ks***@mib.org> 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_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.
Mar 19 '06 #43
Mark McIntyre <ma**********@spamcop.net> writes:
On Sun, 19 Mar 2006 14:49:17 +0100, in comp.lang.c , "Richard G.
Riley" <rg****@gmail.com> 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_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.
Mar 19 '06 #44
On Sun, 19 Mar 2006 13:00:22 UTC, "Vladimir S. Oka"
<no****@btopenworld.com> wrote:
Herbert Rosenau opined:
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 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**********@spamcop.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.com> 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.org>
wrote:
"Herbert Rosenau" <os****@pc-rosenau.de> writes:
On Fri, 17 Mar 2006 18:44:03 UTC, "Vladimir S. Oka"
<no****@btopenworld.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(sizeof(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*******@gmail.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 discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

220 posts views Thread by Brandon J. Van Every | last post: by
92 posts views Thread by Reed L. O'Brien | last post: by
121 posts views Thread by typingcat | last post: by
53 posts views Thread by Deniz Bahar | last post: by
18 posts views Thread by Ramasubbu Ramasubramanian XR (AS/EAB) | last post: by
13 posts views Thread by Jason Huang | last post: by
14 posts views Thread by cat_dog_ass | last post: by
reply views Thread by NPC403 | last post: by
reply views Thread by kermitthefrogpy | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.