By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,180 Members | 1,149 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,180 IT Pros & Developers. It's quick & easy.

IS this a proper way of freeing memory with free()

P: n/a
Hi All,

Here is a small Code,

int main(void)
{
char *p=(char *) malloc(100);
strcpy(p,"Test1234567890");
p=p+10;
free(p);
/*** Is here a memory Leak, because p is now
pointing 10 location past to the start of allocated memory
****/

/** some stuff with p again**/


}
Thanks and Regards,
Raman Chalotra

Feb 1 '07 #1
Share this Question
Share on Google+
171 Replies


P: n/a
Raman wrote:
Hi All,

Here is a small Code,

int main(void)
{
char *p=(char *) malloc(100);
How many times must people here have to say "do not cast the return
value of malloc"? Does anyone read the archive before they post?
strcpy(p,"Test1234567890");
p=p+10;
free(p);
/*** Is here a memory Leak, because p is now
pointing 10 location past to the start of allocated memory
****/
It's completely undefined behaviour. Your toilet might explode. Don't
do it.

--
Ian Collins.
Feb 1 '07 #2

P: n/a
Raman wrote:
char *p=(char *) malloc(100);
char *p = malloc(100 * sizeof *p);

Don't cast the return value from malloc().
strcpy(p,"Test1234567890");
p=p+10;
free(p);
/*** Is here a memory Leak, because p is now
pointing 10 location past to the start of allocated memory
****/
Completely invalid. free() expects a pointer originally returned from one of
the other allocation functions (calloc, malloc, realloc).

NAME
free - free allocated memory

SYNOPSIS
#include <stdlib.h>

void free(void *ptr);

DESCRIPTION
The free() function shall cause the space pointed to by ptr to be
deallocated; that is, made available for further allocation. If ptr is a null
pointer, no action shall occur. Otherwise, if the argument does not match a
pointer earlier returned by the calloc(), malloc(), or realloc() function, or
if the space has been deallocated by a call to free() or realloc(), the
behavior is undefined.

Any use of a pointer that refers to freed space results in undefined
behavior.

Feb 1 '07 #3

P: n/a
Ian Collins wrote:
> char *p=(char *) malloc(100);

How many times must people here have to say "do not cast the return
value of malloc"? Does anyone read the archive before they post?
Basically forever. As long as it's still in books that people read - they'll
keep doing it.
Feb 1 '07 #4

P: n/a
Christopher Layne wrote:
Ian Collins wrote:

>> char *p=(char *) malloc(100);

How many times must people here have to say "do not cast the return
value of malloc"? Does anyone read the archive before they post?


Basically forever. As long as it's still in books that people read - they'll
keep doing it.
So maybe book burning isn't such a bad idea after all.

--
Ian Collins.
Feb 1 '07 #5

P: n/a
"Raman" <ra***********@gmail.comwrote in message
news:11*********************@s48g2000cws.googlegro ups.com...
Hi All,

Here is a small Code,

int main(void)
{
char *p=(char *) malloc(100);
strcpy(p,"Test1234567890");
p=p+10;
free(p);
Problems:

a)You don't test the return value from malloc() to be sure malloc() is able
to grant the memory. There can be some reasons why not ... you should
always test.

b)You may only free() pointers returned by malloc() and friends. The
behavior is undefined. Most likely it will wreck(*) the state of the
runtime library.

(*)The reason for this is that memory allocation is written to be efficient,
and assumes a correct client.

--
David T. Ashley (dt*@e3ft.com)
http://www.e3ft.com (Consulting Home Page)
http://www.dtashley.com (Personal Home Page)
http://gpl.e3ft.com (GPL Publications and Projects)
Feb 1 '07 #6

P: n/a
Raman wrote:
>
int main(void)
{
char *p=(char *) malloc(100);
strcpy(p,"Test1234567890");
p=p+10;
free(p);
/*** Is here a memory Leak, because p is now pointing 10
location past to the start of allocated memory ****/

/** some stuff with p again**/
}
Is here undefined behaviour, because you freed a pointer not
created by malloc. Incidentally, the cast is not required, and bad
because you suppressed the error report from the compiler, due to
failure to #include <stdlib.h>.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Feb 1 '07 #7

P: n/a
Ian Collins wrote:
Christopher Layne wrote:
>Ian Collins wrote:
>>> char *p=(char *) malloc(100);

How many times must people here have to say "do not cast the return
value of malloc"? Does anyone read the archive before they post?

Basically forever. As long as it's still in books that people read
- they'll keep doing it.

So maybe book burning isn't such a bad idea after all.
Are there any reliable estimates as to the number of wood stove
fires annually kindled by BullSchildt books? I have the impression
the value has been dropping for several years. This may be
correlated with the disappearance of Herbs from the C book market.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews

Feb 1 '07 #8

P: n/a
Ian Collins <ia******@hotmail.comwrites:
Raman wrote:
Hi All,

Here is a small Code,

int main(void)
{
char *p=(char *) malloc(100);

How many times must people here have to say "do not cast the return
value of malloc"? Does anyone read the archive before they post?
strcpy(p,"Test1234567890");
p=p+10;
free(p);
/*** Is here a memory Leak, because p is now
pointing 10 location past to the start of allocated memory
****/
It's completely undefined behaviour. Your toilet might explode. Don't
do it.
Its explicitly stated in the book "The C Programming Language" by
Ritchie and Kernighan Second Edition. Thats good enough for me. How
many compilers are *that* strict about the standard anyway? I still
remember a few years ago when one of the versions of gcc (can't remember
specifically) would actually give me a warning if I didn't cast it.

Thats my thoughts on the matter.

Ryan -
Feb 1 '07 #9

P: n/a
Ryan Ply said:
Ian Collins <ia******@hotmail.comwrites:
>Raman wrote:
Hi All,

Here is a small Code,

int main(void)
{
char *p=(char *) malloc(100);

How many times must people here have to say "do not cast the return
value of malloc"? Does anyone read the archive before they post?
strcpy(p,"Test1234567890");
p=p+10;
free(p);
/*** Is here a memory Leak, because p is now
pointing 10 location past to the start of allocated memory
****/
It's completely undefined behaviour. Your toilet might explode. Don't
do it.

Its explicitly stated in the book "The C Programming Language" by
Ritchie and Kernighan Second Edition. Thats good enough for me.
Yes, but K&R remembered to #include <stdlib.h>, didn't they? And in any
case, he wasn't talking about the cast. he was talking about the free().

See K&R's errata page, where they admit that the cast isn't such a great
idea after all (although of course it isn't exactly *wrong* provided you
remember <stdlib.h>).
How
many compilers are *that* strict about the standard anyway? I still
remember a few years ago when one of the versions of gcc (can't remember
specifically) would actually give me a warning if I didn't cast it.
It was probably telling you, indirectly, that you forgot to #include
<stdlib.h- casting malloc, however, does *not* solve the problem gcc was
warning you about; it merely hides the warning message.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 1 '07 #10

P: n/a
Ryan Ply <th******@earthling.netwrote:
Ian Collins <ia******@hotmail.comwrites:
Raman wrote:
Hi All,
>
Here is a small Code,
>
int main(void)
{
char *p=(char *) malloc(100);
How many times must people here have to say "do not cast the return
value of malloc"? Does anyone read the archive before they post?
strcpy(p,"Test1234567890");
p=p+10;
free(p);
/*** Is here a memory Leak, because p is now
pointing 10 location past to the start of allocated memory
****/
>
It's completely undefined behaviour. Your toilet might explode. Don't
do it.
Its explicitly stated in the book "The C Programming Language" by
Ritchie and Kernighan Second Edition. Thats good enough for me.
I guess you refer to the "don't cast the return value of malloc()"
bit. It's explicitely stated in the errata for the book

http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html

that

"The remark about casting the return value of malloc ("the proper
method is to declare ... then explicitly coerce") needs to be
rewritten. The example is correct and works, but the advice is
debatable in the context of the 1988-1989 ANSI/ISO standards.
It's not necessary (given that coercion of void * to ALMOSTANYTYPE *
is automatic), and possibly harmful if malloc, or a proxy for it,
fails to be declared as returning void *. The explicit cast can
cover up an unintended error. On the other hand, pre-ANSI, the cast
was necessary, and it is in C++ also."
How many compilers are *that* strict about the standard anyway? I still
remember a few years ago when one of the versions of gcc (can't remember
specifically) would actually give me a warning if I didn't cast it.
Then that must have been a non-C89 compliant version and the "few
years" is probably more than a decade (or you actually had forgotten
to include <stdlib.h>;-)
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
Feb 1 '07 #11

P: n/a
Richard Heathfield wrote:
[...]
Its explicitly stated in the book "The C Programming Language" by
Ritchie and Kernighan Second Edition. Thats good enough for me.
[...]
See K&R's errata page, where they admit that the cast isn't such a great
idea after all (although of course it isn't exactly *wrong* provided you
remember <stdlib.h>).
[...]

Wasn't the first K&R written prior to adding "void" to the language?
Originally, malloc() et al returned "char *", which meant you had to
use a cast to point to other things.

I maintain code which still #define's VOID to either "void" or "char",
depending on whether the compiler supported void or not. I don't think
there are any current systems we have ported to which do not support
void.

On the other hand, there are still systems with compilers that do not
support function prototypes[1], so there is still the need for things
like:

#if HAS_PROTOTYPES
extern long SomeFunction(int,int);
extern struct foo *AnotherFunction(struct bar *);
#else
extern long SomeFunction();
extern struct foo *AnotherFunction();
#endif
[1] Actually, the compiler recognizes the prototypes, and generates
an error stating that it doesn't support them. At least this
was the case the last time I used that system as recently as
about 2 years ago.

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>

Feb 1 '07 #12

P: n/a
In article <52*************@mid.uni-berlin.de>,
Jens Thoms Toerring <jt@toerring.dewrote:
>How many compilers are *that* strict about the standard anyway? I still
remember a few years ago when one of the versions of gcc (can't remember
specifically) would actually give me a warning if I didn't cast it.
>Then that must have been a non-C89 compliant version and the "few
years" is probably more than a decade (or you actually had forgotten
to include <stdlib.h>;-)
Or perhaps the system's stdlib.h didn't declare malloc()? Given the
existence of malloc.h on some systems, that wouldn't be too
surprising.

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Feb 1 '07 #13

P: n/a
Raman wrote:
Hi All,

Here is a small Code,

int main(void)
{
char *p=(char *) malloc(100);
strcpy(p,"Test1234567890");
p=p+10;
free(p);
/*** Is here a memory Leak, because p is now
pointing 10 location past to the start of allocated memory
****/

/** some stuff with p again**/


}
Others have said it, it's undefined behavior.

Here is a specific example. The numbers are specific to
one implementation I know of. Yours is most likely different.

On my example system, the heap is implemented by maintaining
the free memory blocks in a linked list.

Malloc goes through that list, trying to find a suitable block.
It may cut an existing one into fragments to avoid wasting
too much memory.

When a block is found, say at 0x12000, it gets unlinked from
the list and at the first location in the block the size is
stored. Malloc then returns a pointer to the first address
after that size (0x12004).

Free decrements the pointer by the correct amount (4 bytes),
retrieves the size and hooks the block back into the free list.

On such a system, your code isn't just a memory leak. In your
particular example, free would leak a small block of 10 bytes,
but also hook a free block starting at (p-4) into the free list,
with a size corresponding to the character sequence "3456".

This huge 'free' block is likely to overlap other free and used
memory. The next malloc could now hand out memory which is already
in use.

In other words, you are breaking the internal data structures
of the heap management, and after that anything may happen.

Kind regards,

Iwo

Feb 1 '07 #14

P: n/a
>>>>"CBF" == CBFalconer <cb********@yahoo.comwrites:

CBFAre there any reliable estimates as to the number of wood
CBFstove fires annually kindled by BullSchildt books? I have
CBFthe impression the value has been dropping for several years.
CBFThis may be correlated with the disappearance of Herbs from
CBFthe C book market.

Alas, I was in a bookstore earlier this week, and pride of place in
the C section, meager as it was, was given to _C: the Annotated
Reference_. At least K&R was also there.

(I was looking for the O'Reilly book on SVG, which I had to
special-order. Astounding how many self-evidently *bad* computer
books there are.)

Charlton

--
Charlton Wilbur
cw*****@chromatico.net
Feb 1 '07 #15

P: n/a
Richard Tobin wrote, On 01/02/07 17:06:
In article <52*************@mid.uni-berlin.de>,
Jens Thoms Toerring <jt@toerring.dewrote:
>>How many compilers are *that* strict about the standard anyway? I still
remember a few years ago when one of the versions of gcc (can't remember
specifically) would actually give me a warning if I didn't cast it.
>Then that must have been a non-C89 compliant version and the "few
years" is probably more than a decade (or you actually had forgotten
to include <stdlib.h>;-)

Or perhaps the system's stdlib.h didn't declare malloc()? Given the
existence of malloc.h on some systems, that wouldn't be too
surprising.
The the system's stdlib.h does not declare malloc then it is not C89
compliant and hence is covered by that Jens stated.
--
Flash Gordon
Feb 1 '07 #16

P: n/a
On 01 Feb 2007 08:29:02 -0800, in comp.lang.c , Ryan Ply
<th******@earthling.netwrote:
>Ian Collins <ia******@hotmail.comwrites:
>Raman wrote:
char *p=(char *) malloc(100);

How many times must people here have to say "do not cast the return
value of malloc"? Does anyone read the archive before they post?
Its explicitly stated in the book "The C Programming Language" by
Ritchie and Kernighan Second Edition. Thats good enough for me.
If you're talking about the cast, the Errata list for the book refers
to this as having been a mistake. Also the book is twenty years old,
and C has moved on somewhat since then.
>How
many compilers are *that* strict about the standard anyway? I still
remember a few years ago when one of the versions of gcc (can't remember
specifically) would actually give me a warning if I didn't cast it.
That must have been a C++ compiler. No actual ISO compliant C compiler
has ever been allowed to complain about it. Or else you forgot to
incude stdlib.h of course.
--
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
Feb 1 '07 #17

P: n/a
In article <bd************@news.flash-gordon.me.uk>,
Flash Gordon <sp**@flash-gordon.me.ukwrote:
>>>How many compilers are *that* strict about the standard anyway? I still
remember a few years ago when one of the versions of gcc (can't remember
specifically) would actually give me a warning if I didn't cast it.
>>Then that must have been a non-C89 compliant version and the "few
years" is probably more than a decade (or you actually had forgotten
to include <stdlib.h>;-)
>Or perhaps the system's stdlib.h didn't declare malloc()? Given the
existence of malloc.h on some systems, that wouldn't be too
surprising.
>The the system's stdlib.h does not declare malloc then it is not C89
compliant and hence is covered by that Jens stated.
I read Jens' statement as implying that the version of *gcc* must more
than a decade old. But gcc generally uses the system headers and
libraries, so it might have been the system rather than gcc that was
out-of-date.

-- Richard

--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Feb 1 '07 #18

P: n/a
On Feb 1, 1:50 pm, Charlton Wilbur <cwil...@chromatico.netwrote:
>>>"CBF" == CBFalconer <cbfalco...@yahoo.comwrites:

CBFAre there any reliable estimates as to the number of wood
CBFstove fires annually kindled by BullSchildt books? I have
CBFthe impression the value has been dropping for several years.
CBFThis may be correlated with the disappearance of Herbs from
CBFthe C book market.

Alas, I was in a bookstore earlier this week, and pride of place in
the C section, meager as it was, was given to _C: the Annotated
Reference_. At least K&R was also there.

Well, at least it's a cheap way of picking up a copy of the c89
standard. Well, except for that missing page...

Feb 1 '07 #19

P: n/a
"ro***********@yahoo.com" <ro***********@yahoo.comwrites:
On Feb 1, 1:50 pm, Charlton Wilbur <cwil...@chromatico.netwrote:
>Alas, I was in a bookstore earlier this week, and pride of place in
the C section, meager as it was, was given to _C: the Annotated
Reference_. At least K&R was also there.

Well, at least it's a cheap way of picking up a copy of the c89
standard. Well, except for that missing page...
_C: The Annotated Reference_ != _The Annotated ANSI C Standard_
--
"Your correction is 100% correct and 0% helpful. Well done!"
--Richard Heathfield
Feb 1 '07 #20

P: n/a
On Feb 1, 5:08 pm, Ben Pfaff <b...@cs.stanford.eduwrote:
"robertwess...@yahoo.com" <robertwess...@yahoo.comwrites:
Well, at least it's a cheap way of picking up a copy of the c89
standard. Well, except for that missing page...

_C: The Annotated Reference_ != _The Annotated ANSI C Standard_

Mea culpa.

Feb 1 '07 #21

P: n/a
ri*****@cogsci.ed.ac.uk (Richard Tobin) writes:
In article <52*************@mid.uni-berlin.de>,
Jens Thoms Toerring <jt@toerring.dewrote:
How many compilers are *that* strict about the standard anyway? I still
remember a few years ago when one of the versions of gcc (can't remember
specifically) would actually give me a warning if I didn't cast it.
Then that must have been a non-C89 compliant version and the "few
years" is probably more than a decade (or you actually had forgotten
to include <stdlib.h>;-)

Or perhaps the system's stdlib.h didn't declare malloc()? Given the
existence of malloc.h on some systems, that wouldn't be too
surprising.
Actually, it would be very surprising. Quoting the Rationale:

The header <stdlib.hwas invented by the C89 Committee to hold an
assortment of functions that were otherwise homeless.

There's never been a specification for <stdlib.hthat didn't include
a declaration of malloc().

It's far more likely that somebody forgot the "#include <stdlib.h>",
causing the compiler to assume that malloc() returns int.

--
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.
Feb 2 '07 #22

P: n/a
Charlton Wilbur <cw*****@chromatico.netwrites:
>>>"CBF" == CBFalconer <cb********@yahoo.comwrites:

CBFAre there any reliable estimates as to the number of wood
CBFstove fires annually kindled by BullSchildt books? I have
CBFthe impression the value has been dropping for several years.
CBFThis may be correlated with the disappearance of Herbs from
CBFthe C book market.

Alas, I was in a bookstore earlier this week, and pride of place in
the C section, meager as it was, was given to _C: the Annotated
Reference_. At least K&R was also there.
[...]

Are you sure about that title? Schildt has a book called _C: The
Complete Reference_, and another (now out of print) called _The
Annotated ANSI C Standard_. The latter was a useful way to get a copy
of the C90 standard, but the annotations were positively dangerous.

--
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.
Feb 2 '07 #23

P: n/a
Ryan Ply wrote:
>
.... snip casting malloc ...
>
Its explicitly stated in the book "The C Programming Language" by
Ritchie and Kernighan Second Edition. Thats good enough for me.
How many compilers are *that* strict about the standard anyway?
I still remember a few years ago when one of the versions of gcc
(can't remember specifically) would actually give me a warning if
I didn't cast it.
You were using a C++ compiler. Read the errata for K&R.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>
Feb 2 '07 #24

P: n/a
Kenneth Brody wrote:
>
.... snip ...
>
I maintain code which still #define's VOID to either "void" or
"char", depending on whether the compiler supported void or not.
I don't think there are any current systems we have ported to
which do not support void.
Very bad. There is a major difference (after expanding the macro)
between:

void foo(i) {
...
return ?;
}
and
char foo(i) {
...
return ?;
}

one or t'other will be a compilation error.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>
Feb 2 '07 #25

P: n/a
Mark McIntyre <ma**********@spamcop.netwrites:
[...]
That must have been a C++ compiler. No actual ISO compliant C compiler
has ever been allowed to complain about it. Or else you forgot to
incude stdlib.h of course.
Strictly speaking, a compiler is allowed to complain about anything it
likes. But yes, if it complains about a malloc() call with no cast,
it's probably because <stdlib.hwasn't included or because it's a C++
compiler.

--
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.
Feb 2 '07 #26

P: n/a
CBFalconer <cb********@yahoo.comwrites:

You were using a C++ compiler.
From the gcc man page:
"For any given input file, the file name suffix determines what kind of
compilation is done"

My file extensions are *.c (lowercase), therefore a C compiler.
Read the errata for K&R.
I see in the errata these fun phrases. "the advice is debatable",
"possibly harmful", "can cover up an unintended error".

Lots of stuff that could, possibly, maybe happen. As for the "possibly
harmful for malloc" comment, its if malloc fails to be declared as
returning void *. Is there an place where it isn't? I suppose my point
is that I don't understand why I should program for things that have a
firm chance of a definite maybe of happening.

Ryan -
Feb 2 '07 #27

P: n/a
>>>>"KT" == Keith Thompson <ks***@mib.orgwrites:
> Alas, I was in a bookstore earlier this week, and pride of
place in the C section, meager as it was, was given to _C: the
Annotated Reference_. At least K&R was also there.
KT[...]

KTAre you sure about that title?

Honestly, no. I have K&R and Harbison & Steele on my shelf; I
registered a big thick book by Schildt, and as I wasn't even looking
for a C reference, I didn't look much closer.

Charlton

--
Charlton Wilbur
cw*****@chromatico.net
Feb 2 '07 #28

P: n/a
Ryan Ply wrote:
Lots of stuff that could, possibly, maybe happen. As for the "possibly
harmful for malloc" comment, its if malloc fails to be declared as
returning void *. Is there an place where it isn't? I suppose my point
is that I don't understand why I should program for things that have a
firm chance of a definite maybe of happening.

Ryan -
Okay, why bother casting? Does it make you feel better? The language rules are
in full effect if you are not explicitly casting the return value from any of
the allocation functions (or any void * returning function for that matter).
Do you not trust this?

By casting the return value, you're reinstilling a misunderstanding of
the "rules" if you will.

Are you afraid of void *? It's your friend you know.
Feb 2 '07 #29

P: n/a
Ryan Ply said:
CBFalconer <cb********@yahoo.comwrites:
>Read the errata for K&R.

I see in the errata these fun phrases. "the advice is debatable",
"possibly harmful", "can cover up an unintended error".

Lots of stuff that could, possibly, maybe happen.
And, in fact, has happened on quite a few occasions.
As for the "possibly
harmful for malloc" comment, its if malloc fails to be declared as
returning void *. Is there an place where it isn't?
Yes, your program, if you fail to #include <stdlib.h>
I suppose my point
is that I don't understand why I should program for things that have a
firm chance of a definite maybe of happening.
Wait a moment. Whilst there are certainly very, very good reasons why you
*should* program for things that have a firm chance of a definite maybe of
happening, let's just look at the effort involved here in the two
techniques:

Technique 1 (your way) requires you to include the <stdlib.hheader and
requires you to type a pointer cast and requires you to fix the cast if the
type changes.

Technique 2 (which is what we like to call "the right way") requires you to
include the header.

So we're suggesting that you might like to do less work and get a better,
more maintainable program as a result. But hey, no pressure - if you want
to keep doing it in some way other than the right way, that's up to you - I
mean, some people just love to type, right?

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 2 '07 #30

P: n/a
Ryan Ply <th******@earthling.netwrote:
Lots of stuff that could, possibly, maybe happen. As for the "possibly
harmful for malloc" comment, its if malloc fails to be declared as
returning void *. Is there an place where it isn't? I suppose my point
is that I don't understand why I should program for things that have a
firm chance of a definite maybe of happening.
Good point. So why cast at all? It solves nothing that deserves solving,
it involves more keypresses, and it does degrade the warning value of
real casts. The last one is the killer, IMO: casting malloc() is like
hanging a High Voltage sign on every home outlet. It means that when you
_need_ the warning, you've been trained to think "Oh, just another
meaningless High Voltage sign/pointer cast, let's ignore it", and get
zapped to a crisp/get your program segfaulted. Don't train yourself not
to pay attention; don't cast malloc().

Richard
Feb 2 '07 #31

P: n/a
ri*****@cogsci.ed.ac.uk (Richard Tobin) wrote:
In article <bd************@news.flash-gordon.me.uk>,
Flash Gordon <sp**@flash-gordon.me.ukwrote:
>Then that must have been a non-C89 compliant version and the "few
years" is probably more than a decade (or you actually had forgotten
to include <stdlib.h>;-)
Or perhaps the system's stdlib.h didn't declare malloc()? Given the
existence of malloc.h on some systems, that wouldn't be too
surprising.
The the system's stdlib.h does not declare malloc then it is not C89
compliant and hence is covered by that Jens stated.

I read Jens' statement as implying that the version of *gcc* must more
than a decade old. But gcc generally uses the system headers and
libraries, so it might have been the system rather than gcc that was
out-of-date.
Possibly, but that's a poor cop-out, IMO. You work with an
implementation, not with two half-implementations. Ganoo (i.c.) passing
the buck to Aitch Pee (e.g.), and Aitch Pee passing the buck back to
Ganoo, makes both of them guilty for together delivering a broken
implementation, not neither of them. Neither the Standard nor the end
user cares, nor should they care, that parts of the implementation came
from different suppliers.

Richard
Feb 2 '07 #32

P: n/a
In article <45*****************@news.xs4all.nl>,
Richard Bos <rl*@hoekstra-uitgeverij.nlwrote:
>I read Jens' statement as implying that the version of *gcc* must more
than a decade old. But gcc generally uses the system headers and
libraries, so it might have been the system rather than gcc that was
out-of-date.
>Possibly, but that's a poor cop-out, IMO.
It might be a cop-out if someone from the gcc team said it, but I have
nothing to do with them, so it's just a possible explanation (perhaps
an unlikely one, as some have said).

-- Richard
--
"Consideration shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.
Feb 2 '07 #33

P: n/a
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
Good point. So why cast at all? It solves nothing that deserves solving,
it involves more keypresses, and it does degrade the warning value of
real casts.
Abbrev mode is your friend, assuming you use emacs that is. Some quick
reading of man pages as to proper compiler flags will solve the
warnings.
Also to Richard Heathfield:
Technique 1 (your way) requires you to include the <stdlib.hheader
and requires you to type a pointer cast and requires you to fix the
cast if the type changes.
Technique 2 (which is what we like to call "the right way") requires
you to include the header.
So we're suggesting that you might like to do less work and get a
better, more maintainable program as a result. But hey, no pressure -
if you want to keep doing it in some way other than the right way,
that's up to you - I mean, some people just love to type, right?
stdlib.h is has been in my .c template for as long as I can remember,
I'm not sure why this newsgroup assumes it isn't. All I've said that
would allude to it not being there was in reference to an old gcc
compiler, probably 2.95 or earlier.

Its also not more keystrokes for me, I have abbrev lists, it also make
my code cleaner as I can compare the number of 'stars' * in the cast
versus the number inside the malloc and have virtually eliminated my
pointer problems by doing that. I'm suggesting that I'm doing less work
and getting a more maintainable program as a result. That's just me.

Ryan -
Feb 2 '07 #34

P: n/a
Ryan Ply <th******@earthling.netwrites:
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
>Good point. So why cast at all? It solves nothing that deserves solving,
it involves more keypresses, and it does degrade the warning value of
real casts.

Abbrev mode is your friend, assuming you use emacs that is.
You have set up a tool to help you add unnecessary casts?
Some quick
reading of man pages as to proper compiler flags will solve the
warnings.
I think you miss Richard Bos's point. I think he means that one huge
advantage of casts is they alert one to problems. If you need one,
then things have got sticky. If you use them where they are not
needed they can't be used as a strong flag, drawing the reader's
attention to important problems.
Also to Richard Heathfield:
>Technique 1 (your way) requires you to include the <stdlib.hheader
and requires you to type a pointer cast and requires you to fix the
cast if the type changes.
>Technique 2 (which is what we like to call "the right way") requires
you to include the header.
>So we're suggesting that you might like to do less work and get a
better, more maintainable program as a result. But hey, no pressure -
if you want to keep doing it in some way other than the right way,
that's up to you - I mean, some people just love to type, right?

stdlib.h is has been in my .c template for as long as I can remember,
I'm not sure why this newsgroup assumes it isn't. All I've said that
would allude to it not being there was in reference to an old gcc
compiler, probably 2.95 or earlier.

Its also not more keystrokes for me, I have abbrev lists, it also make
my code cleaner as I can compare the number of 'stars' * in the cast
versus the number inside the malloc and have virtually eliminated my
pointer problems by doing that.
What problems? If you use the recommended idiom:

p = malloc(<exp* sizeof *p);

you know the type will be correct, and no casts!
I'm suggesting that I'm doing less work
and getting a more maintainable program as a result. That's just
me.
Yes, just you!

--
Ben.
Feb 2 '07 #35

P: n/a
On 02 Feb 2007 08:33:03 -0800, in comp.lang.c , Ryan Ply
<th******@earthling.netwrote:
>rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
>Good point. So why cast at all? It solves nothing that deserves solving,
it involves more keypresses, and it does degrade the warning value of
real casts.

Abbrev mode is your friend, assuming you use emacs that is.
You've programmed your environment to automatically do something
unnecessary and potentially harmful. Ask yourself why you'd want to do
that.
>Some quick
reading of man pages as to proper compiler flags will solve the
warnings.
You miss the point - with the cast in place, warnings are
/suppressed/, even when they would have been valid. With the cast
removed, the only warnings you should get are if you actually did make
a mistake.
--
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
Feb 2 '07 #36

P: n/a
Ryan Ply wrote:
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:

>>Good point. So why cast at all? It solves nothing that deserves solving,
it involves more keypresses, and it does degrade the warning value of
real casts.


Abbrev mode is your friend, assuming you use emacs that is. Some quick
reading of man pages as to proper compiler flags will solve the
warnings.
Solve the warnings? Warnings are your friend, fix them, don't sweep
them under the the rug.

--
Ian Collins.
Feb 2 '07 #37

P: n/a
Ryan Ply wrote:
Its also not more keystrokes for me, I have abbrev lists, it also make
my code cleaner as I can compare the number of 'stars' * in the cast
versus the number inside the malloc and have virtually eliminated my
pointer problems by doing that. I'm suggesting that I'm doing less work
and getting a more maintainable program as a result. That's just me.

Ryan -
But you're being irrational and refusing to change your ways after being shown
that it is a pointless and sometimes dangerous way.

Go read up on pointers of type void.
Feb 2 '07 #38

P: n/a
Ben Bacarisse wrote:
Ryan Ply <th******@earthling.netwrites:
>>
.... snip ...
>>
stdlib.h is has been in my .c template for as long as I can
remember, I'm not sure why this newsgroup assumes it isn't.
All I've said that would allude to it not being there was in
reference to an old gcc compiler, probably 2.95 or earlier.
Piggybacking here.

Why should you always include stdio.h? In many cases it is
unnecessary, and even not available (in some embedded systems). An
example is my implementation of strlcpy/cat, which is usable
unchanged on such systems. Just put in the things you need. The
other attitude leads to such abortions as windows.h.

--
<http://www.cs.auckland.ac.nz/~pgut001/pubs/vista_cost.txt>

"A man who is right every time is not likely to do very much."
-- Francis Crick, co-discover of DNA
"There is nothing more amazing than stupidity in action."
-- Thomas Matthews
Feb 3 '07 #39

P: n/a
CBFalconer said:
Ben Bacarisse wrote:
>Ryan Ply <th******@earthling.netwrites:
>>>
... snip ...
>>>
stdlib.h is has been in my .c template for as long as I can
remember, I'm not sure why this newsgroup assumes it isn't.
All I've said that would allude to it not being there was in
reference to an old gcc compiler, probably 2.95 or earlier.

Piggybacking here.

Why should you always include stdio.h?
Why indeed? But he didn't claim you should, or that he does, always include
<stdio.h- he was actually referring to <stdlib.h>, and he doesn't even
claim always to include /that/ - he merely said it was in his ".c
template". Presumably that's some kind of stamp with which he churns out C
source file skeleta - and presumably he can remove <stdlib.hfrom a given
source if it turns out not to be required therein.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 3 '07 #40

P: n/a
Ryan Ply <th******@earthling.netwrote:
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
Good point. So why cast at all? It solves nothing that deserves solving,
it involves more keypresses, and it does degrade the warning value of
real casts.

Abbrev mode is your friend, assuming you use emacs that is. Some quick
reading of man pages as to proper compiler flags will solve the
warnings.
I don't use Emac-OS, and even if I did, abrv. mode would not solve the
more important problem of making the malloc()-caster less attentive. As
for "solving" the warnings, that's like "solving" a stinging pain in
your right side by taking morphine. Yes, it _does_ get rid of the pain,
but you'll still die of a burst appendix sooner or later. It's better
get rid of the cause of the pain (read: warning messages) than to ignore
it.

Richard
Feb 5 '07 #41

P: n/a
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
Ryan Ply <th******@earthling.netwrote:
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
Good point. So why cast at all? It solves nothing that deserves solving,
it involves more keypresses, and it does degrade the warning value of
real casts.
Abbrev mode is your friend, assuming you use emacs that is. Some quick
reading of man pages as to proper compiler flags will solve the
warnings.

I don't use Emac-OS, and even if I did, abrv. mode would not solve the
more important problem of making the malloc()-caster less attentive. As
for "solving" the warnings, that's like "solving" a stinging pain in
your right side by taking morphine. Yes, it _does_ get rid of the pain,
but you'll still die of a burst appendix sooner or later. It's better
get rid of the cause of the pain (read: warning messages) than to ignore
it.
People just like reading whatever they want instead of whats on the
screen in front of them. Someone said that by casting it would hide or
mask the compilers warnings to me. I put extra flags in so that these
warnings return as if nothing happened. Thus "solved". I program for
real targets, not would be possible maybe in some day embedded targets
20 years form now possibly. That is how specific compiler options are
safe to use for me. When I get a project with a vague target then
things will be different, but that hasn't happened to date.
Ryan -
Feb 6 '07 #42

P: n/a
Ryan Ply said:
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
<snip>
>It's better get rid of the cause of the pain (read: warning
messages) than to ignore it.

People just like reading whatever they want instead of whats on the
screen in front of them. Someone said that by casting it would hide
or
mask the compilers warnings to me.
Yes, it may well hide or mask the warning, in the same way (as Richard B
graphically points out) that morphine hides or masks the pain of a
burst appendix. But just as morphine doesn't cure a burst appendix,
neither does casting malloc cure the problem that causes the compiler
to generate a warning.
I put extra flags in so that these
warnings return as if nothing happened. Thus "solved". I program for
real targets, not would be possible maybe in some day embedded targets
20 years form now possibly.
In this newsgroup, we have had people post code which exhibits serious
behavioral problems, and these problems vanished like the dawn mist
when they followed our advice to remove the cast and add the
appropriate header instead. This is not an academic issue.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
Feb 6 '07 #43

P: n/a
Ryan Ply wrote:
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
Ryan Ply <th******@earthling.netwrote:
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
>
Good point. So why cast at all? It solves nothing that deserves solving,
it involves more keypresses, and it does degrade the warning value of
real casts.
>
Abbrev mode is your friend, assuming you use emacs that is. Some quick
reading of man pages as to proper compiler flags will solve the
warnings.
I don't use Emac-OS, and even if I did, abrv. mode would not solve the
more important problem of making the malloc()-caster less attentive. As
for "solving" the warnings, that's like "solving" a stinging pain in
your right side by taking morphine. Yes, it _does_ get rid of the pain,
but you'll still die of a burst appendix sooner or later. It's better
get rid of the cause of the pain (read: warning messages) than to ignore
it.

People just like reading whatever they want instead of whats on the
screen in front of them. Someone said that by casting it would hide or
mask the compilers warnings to me. I put extra flags in so that these
warnings return as if nothing happened. Thus "solved". I program for
real targets, not would be possible maybe in some day embedded targets
20 years form now possibly. That is how specific compiler options are
safe to use for me. When I get a project with a vague target then
things will be different, but that hasn't happened to date.
Eliminating non-essential casts is not mutually exclusive with
programming for "real targets" or whatever else you mean.

Feb 6 '07 #44

P: n/a
Ryan Ply <th******@earthling.netwrote:
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
I don't use Emac-OS, and even if I did, abrv. mode would not solve the
more important problem of making the malloc()-caster less attentive. As
for "solving" the warnings, that's like "solving" a stinging pain in
your right side by taking morphine. Yes, it _does_ get rid of the pain,
but you'll still die of a burst appendix sooner or later. It's better
get rid of the cause of the pain (read: warning messages) than to ignore
it.

People just like reading whatever they want instead of whats on the
screen in front of them. Someone said that by casting it would hide or
mask the compilers warnings to me. I put extra flags in so that these
warnings return as if nothing happened. Thus "solved".
Wrong.
I program for real targets, not would be possible maybe in some day
embedded targets 20 years form now possibly.
The meaning of that sentence is as muddled as its grammar.
That is how specific compiler options are safe to use for me.
Wrong.
When I get a project with a vague target then
things will be different, but that hasn't happened to date.
But don't mind me; just don't come whining when your habit of ignoring
valid warnings comes back to bite you in the arse.

Richard
Feb 7 '07 #45

P: n/a
Richard Bos wrote:
Ryan Ply <th******@earthling.netwrote:
>rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
>>I don't use Emac-OS, and even if I did, abrv. mode would not solve the
more important problem of making the malloc()-caster less attentive. As
for "solving" the warnings, that's like "solving" a stinging pain in
your right side by taking morphine. Yes, it _does_ get rid of the pain,
but you'll still die of a burst appendix sooner or later. It's better
get rid of the cause of the pain (read: warning messages) than to ignore
it.
People just like reading whatever they want instead of whats on the
screen in front of them. Someone said that by casting it would hide or
mask the compilers warnings to me. I put extra flags in so that these
warnings return as if nothing happened. Thus "solved".

Wrong.
What's wrong? Ryan Ply said couple of times that he gets his warnings,
and indeed, for instance gcc warns about undeclared malloc() with or
without cast. Cast *may* (perhaps) suppress the warning, but it doesn't
for Ryan, so he's good. Are there other other reasons not to cast
(except the obvious one, why cast if it works fine without cast)?

Yevgen
Feb 7 '07 #46

P: n/a
Yevgen Muntyan <mu****************@tamu.eduwrote:
Richard Bos wrote:
Ryan Ply <th******@earthling.netwrote:
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:

I don't use Emac-OS, and even if I did, abrv. mode would not solve the
more important problem of making the malloc()-caster less attentive. As
for "solving" the warnings, that's like "solving" a stinging pain in
your right side by taking morphine. Yes, it _does_ get rid of the pain,
but you'll still die of a burst appendix sooner or later. It's better
get rid of the cause of the pain (read: warning messages) than to ignore
it.
People just like reading whatever they want instead of whats on the
screen in front of them. Someone said that by casting it would hide or
mask the compilers warnings to me. I put extra flags in so that these
warnings return as if nothing happened. Thus "solved".
Wrong.

What's wrong?
Stomped over != solved.
Are there other other reasons not to cast
RTFThread. It's right up there ^^^.

Richard
Feb 7 '07 #47

P: n/a
Richard Bos wrote:
Yevgen Muntyan <mu****************@tamu.eduwrote:
>Richard Bos wrote:
>>Ryan Ply <th******@earthling.netwrote:

rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:

I don't use Emac-OS, and even if I did, abrv. mode would not solve the
more important problem of making the malloc()-caster less attentive. As
for "solving" the warnings, that's like "solving" a stinging pain in
your right side by taking morphine. Yes, it _does_ get rid of the pain,
but you'll still die of a burst appendix sooner or later. It's better
get rid of the cause of the pain (read: warning messages) than to ignore
it.
People just like reading whatever they want instead of whats on the
screen in front of them. Someone said that by casting it would hide or
mask the compilers warnings to me. I put extra flags in so that these
warnings return as if nothing happened. Thus "solved".
Wrong.
What's wrong?

Stomped over != solved.
Stomped over *what*? I believe you are saying he suppresses
warnings using cast. It's not the case. Are you talking about something
else?
>Are there other other reasons not to cast

RTFThread. It's right up there ^^^.
Sorry, I've seen only one bad thing - suppressing warnings. I might
have missed something, of course. I've seen "cast hides the problems",
but what problems? If compiler warns you about missing prototype, you
add missing #include, and then you're totally good - prototype is in
place, casting void* to whatever* is fine; if whatever* is not the
right type you get another warning (or compilation error). What exactly
are those problems?

Yevgen
Feb 7 '07 #48

P: n/a
On Wed, 07 Feb 2007 15:53:10 GMT, in comp.lang.c , Yevgen Muntyan
<mu****************@tamu.eduwrote:
>Richard Bos wrote:
>Yevgen Muntyan <mu****************@tamu.eduwrote:
>>Richard Bos wrote:
Ryan Ply <th******@earthling.netwrote:

rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
>
>I don't use Emac-OS, and even if I did, abrv. mode would not solve the
>more important problem of making the malloc()-caster less attentive. As
>for "solving" the warnings, that's like "solving" a stinging pain in
>your right side by taking morphine. Yes, it _does_ get rid of the pain,
>but you'll still die of a burst appendix sooner or later. It's better
>get rid of the cause of the pain (read: warning messages) than to ignore
>it.
People just like reading whatever they want instead of whats on the
screen in front of them. Someone said that by casting it would hide or
mask the compilers warnings to me. I put extra flags in so that these
warnings return as if nothing happened. Thus "solved".
Wrong.
What's wrong?

Stomped over != solved.

Stomped over *what*? I believe you are saying he suppresses
warnings using cast. It's not the case.
No, he's saying that its not a good idea to hide warnings.
>Sorry, I've seen only one bad thing - suppressing warnings. I might
have missed something, of course. I've seen "cast hides the problems",
but what problems?
This is practically a FAQ - oh look, it is. In fact its a whole bunch
of them...
--
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
Feb 7 '07 #49

P: n/a
Yevgen Muntyan wrote:
Richard Bos wrote:
Yevgen Muntyan <mu****************@tamu.eduwrote:
Richard Bos wrote:
Ryan Ply <th******@earthling.netwrote:
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:

I don't use Emac-OS, and even if I did, abrv. mode would not solve the
more important problem of making the malloc()-caster less attentive. As
for "solving" the warnings, that's like "solving" a stinging pain in
your right side by taking morphine. Yes, it _does_ get rid of the pain,
but you'll still die of a burst appendix sooner or later. It's better
get rid of the cause of the pain (read: warning messages) than to ignore
it.
People just like reading whatever they want instead of whats on the
screen in front of them. Someone said that by casting it would hide or
mask the compilers warnings to me. I put extra flags in so that these
warnings return as if nothing happened. Thus "solved".
Wrong.
What's wrong?
<snip>
Are there other other reasons not to cast
RTFThread. It's right up there ^^^.

Sorry, I've seen only one bad thing - suppressing warnings. I might
have missed something, of course. I've seen "cast hides the problems",
but what problems? If compiler warns you about missing prototype, you
add missing #include, and then you're totally good - prototype is in
place, casting void* to whatever* is fine; if whatever* is not the
right type you get another warning (or compilation error). What exactly
are those problems?
Without a prototype, *alloc() are assumed to return an int. They, of
course, return a void pointer value. Assigning an int value, which is
itself derived from a void pointer value, to a pointer to T should
produce a diagnostic, if not for the unneccessary cast. So the casting
hides the fact that no prototype is in scope, and it forces a type
conversion which is not guaranteed to produce meaningful results on
all implementations.

Feb 7 '07 #50

171 Replies

This discussion thread is closed

Replies have been disabled for this discussion.