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

AMD opteron 64

P: n/a
Hello,

I have a test program that is compiled fine on a 32 bits redhat linux using gcc :
***********************
main (argc, argv)
int argc;
char *argv[];
{
int *ka;
int nka;

/* allocation dynamique entiere */
ka = (int *) malloc(nka * sizeof(int));
if (!ka) {
printf ("<ERROR> : Out of heap space (malloc) !\n");
printf ("<ERROR> : %d int words required\n", nka);
exit (-1);
}
}
***********************

But under linux suse AMD opteron 64, i get this message from the compiler :

warning: cast to pointer from integer of different size

Any explanation ?

Regards,
Lionel.
--
-=O=------------------------------------------=O=-
Lionel Valéro
Analyste Informatique Département Génie Chimique
École Polytechnique de Montréal
C.P. 6079, succ. centre-ville
Montréal (Québec) H3C 3A7
Tel: (514) 340 - 4711 # 4805 / C552
Fax: (514) 340 - 4159
-=O=------------------------------------------=O=-

Nov 13 '05 #1
Share this Question
Share on Google+
54 Replies


P: n/a
Lionel Valero <li***********@polymtl.ca> writes:
main (argc, argv)
int argc;
char *argv[];
{
int *ka;
int nka;

/* allocation dynamique entiere */
ka = (int *) malloc(nka * sizeof(int));


I don't recommend casting the return value of malloc():

* The cast is not required in ANSI C.

* Casting its return value can mask a failure to #include
<stdlib.h>, which leads to undefined behavior.

* If you cast to the wrong type by accident, odd failures can
result.

In fact, the second problem is your problem here. Fix it.

When calling malloc(), I recommend using the sizeof operator on
the object you are allocating, not on the type. For instance,
*don't* write this:

int *x = malloc (sizeof (int) * 128); /* Don't do this! */

Instead, write it this way:

int *x = malloc (sizeof *x * 128);

There's a few reasons to do it this way:

* If you ever change the type that `x' points to, it's not
necessary to change the malloc() call as well.

This is more of a problem in a large program, but it's still
convenient in a small one.

* Taking the size of an object makes writing the statement
less error-prone. You can verify that the sizeof syntax is
correct without having to look at the declaration.

--
char a[]="\n .CJacehknorstu";int putchar(int);int main(void){unsigned long b[]
={0x67dffdff,0x9aa9aa6a,0xa77ffda9,0x7da6aa6a,0xa6 7f6aaa,0xaa9aa9f6,0x1f6},*p=
b,x,i=24;for(;p+=!*p;*p/=4)switch(x=*p&3)case 0:{return 0;for(p--;i--;i--)case
2:{i++;if(1)break;else default:continue;if(0)case 1:putchar(a[i&15]);break;}}}
Nov 13 '05 #2

P: n/a
In article <nE*******************@charlie.risq.qc.ca>,
li***********@polymtl.ca says...
Hello,

I have a test program that is compiled fine on a 32 bits redhat linux using gcc :
***********************
main (argc, argv)
int argc;
char *argv[];
{
int *ka;
int nka;

/* allocation dynamique entiere */
ka = (int *) malloc(nka * sizeof(int));
if (!ka) {
printf ("<ERROR> : Out of heap space (malloc) !\n");
printf ("<ERROR> : %d int words required\n", nka);
exit (-1);
}
}
***********************

But under linux suse AMD opteron 64, i get this message from the compiler :

warning: cast to pointer from integer of different size

Any explanation ?


At a quick glance, you seem to have left out a proper header for malloc.
The compiler doesn't automagically know what "malloc" means without one.
Also, the cast is not required in C, and helps to hide this omission from
you, thereby making it harder to diagnose.

--
Randy Howard _o
2reply remove FOOBAR \<,
______________________()/ ()______________________________________________
SCO Spam-magnet: po********@sco.com
Nov 13 '05 #3

P: n/a
> ka = (int *) malloc(nka * sizeof(int));

No cast.

Also, sizeof( void* ) might not equal sizeof( int* ).

--
The designer of the experimental, SMP and HyperThread friendly, AppCore
library.

http://AppCore.home.comcast.net
Nov 13 '05 #4

P: n/a
On Mon, 01 Dec 2003 18:21:07 GMT, Lionel Valero <li***********@polymtl.ca>
wrote:
Hello,

I have a test program that is compiled fine on a 32 bits redhat linux using gcc :
***********************
main (argc, argv)
int argc;
char *argv[];
{
int *ka;
int nka;

/* allocation dynamique entiere */
ka = (int *) malloc(nka * sizeof(int));
if (!ka) {
printf ("<ERROR> : Out of heap space (malloc) !\n");
printf ("<ERROR> : %d int words required\n", nka);
exit (-1);
}
}
***********************

But under linux suse AMD opteron 64, i get this message from the compiler :

warning: cast to pointer from integer of different size

Any explanation ?


Yes. You neglected to
#include <stdlib.h>
which defines the malloc() function's return value.

Since you did not do this, the compiler assumed that malloc() returned the
default type (int), and saw that you forced a conversion from (int) to (int *)
in your code. The compiler issued the warning based on this.

The fix is to
a) include <stdlib.h> in your code, and
b) remove the unnecessary case of malloc()'s return value.

--
Lew Pitcher
IT Consultant, Enterprise Technology Solutions
Toronto Dominion Bank Financial Group

(Opinions expressed are my own, not my employers')
Nov 13 '05 #5

P: n/a
I forgto the headers :
#include <stdio.h>
#include <sys/types.h>
#include <time.h>
Lionel Valero wrote:
Hello,

I have a test program that is compiled fine on a 32 bits redhat linux
using gcc :
***********************
main (argc, argv)
int argc;
char *argv[];
{
int *ka;
int nka;

/* allocation dynamique entiere */
ka = (int *) malloc(nka * sizeof(int));
if (!ka) {
printf ("<ERROR> : Out of heap space (malloc) !\n");
printf ("<ERROR> : %d int words required\n", nka);
exit (-1);
}
}
***********************

But under linux suse AMD opteron 64, i get this message from the compiler :

warning: cast to pointer from integer of different size

Any explanation ?

Regards,
Lionel.


--
-=O=------------------------------------------=O=-
Lionel Valéro
Analyste Informatique Département Génie Chimique
École Polytechnique de Montréal
C.P. 6079, succ. centre-ville
Montréal (Québec) H3C 3A7
Tel: (514) 340 - 4711 # 4805 / C552
Fax: (514) 340 - 4159
-=O=------------------------------------------=O=-
Nov 13 '05 #6

P: n/a
In article <6d*******************@charlie.risq.qc.ca>,
li***********@polymtl.ca says...
I forgto the headers :
#include <stdio.h>
#include <sys/types.h>
#include <time.h>
<sys/types.h> does not seem to be necessary for what you have below
and you will find out that it isn't portable either.

<time.h> also does not seem to be necessary, but at least is standard.

What is necessary: <stdlib.h>, as has been pointed out already in this
thread.


Lionel Valero wrote:
Hello,

I have a test program that is compiled fine on a 32 bits redhat linux
using gcc :
***********************
main (argc, argv)
int argc;
char *argv[];
{
int *ka;
int nka;

/* allocation dynamique entiere */
ka = (int *) malloc(nka * sizeof(int));
if (!ka) {
printf ("<ERROR> : Out of heap space (malloc) !\n");
printf ("<ERROR> : %d int words required\n", nka);
exit (-1);
}
}
***********************

But under linux suse AMD opteron 64, i get this message from the compiler :

warning: cast to pointer from integer of different size

Any explanation ?

Regards,
Lionel.



--
Randy Howard _o
2reply remove FOOBAR \<,
______________________()/ ()______________________________________________
SCO Spam-magnet: po********@sco.com
Nov 13 '05 #7

P: n/a
On Mon, 1 Dec 2003 19:00:18 UTC, Lionel Valero
<li***********@polymtl.ca> wrote:
I forgto the headers :
#include <stdio.h>
#include <sys/types.h>
#include <time.h>

You forgot to include stdlib.h again Lionel Valero wrote:

ka = (int *) malloc(nka * sizeof(int));


And this cast hides the error that you forgot to include the header in
redhat linux.
Casting the result from a function that returns void* is always an
error.

--
Tschau/Bye
Herbert

To buy eComStation 1.1 in germany visit http://www.pc-rosenau.de

Nov 13 '05 #8

P: n/a
Lionel Valero wrote:
I have a test program
that is compiled fine on a 32 bits redhat linux using gcc :
*************** cat malloc.c #include <stdlib.h>
#include <stdio.h>

int main (int argc, char* argv[]) {
int nka = atoi(argv[1]);

/* allocation dynamique entiere */
int* ka = (int*)malloc(nka*sizeof(int));
if (NULL == ka) {
fprintf(stderr, "<ERROR>: Out of free storage (malloc)!\n");
fprintf(stderr, "<ERROR>: %d int words required\n", nka);
exit (EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
gcc -Wall -std=c99 -pedantic -o malloc malloc.c
./malloc 13
./malloc 999999999999 <ERROR>: Out of free storage (malloc)!
<ERROR>: 2147483647 int words required
***********************

But under linux suse AMD opteron 64, I get this message from the compiler:

warning: cast to pointer from integer of different size

Any explanation?


You need to include stdlib.h which declares malloc.

Nov 13 '05 #9

P: n/a
Ben Pfaff wrote:
I don't recommend casting the return value of malloc():

* The cast is not required in ANSI C.
But an ANSI/ISO C++ compiler will complain.
* Casting its return value can mask a failure to
#include <stdlib.h>, which leads to undefined behavior.
No! It may mask the fact that malloc was not declared
but a good C compiler will warn you about that.
* If you cast to the wrong type by accident,
odd failures can result.
Can you show us an example?
In fact, the second problem is your problem here. Fix it.

When calling malloc(), I recommend using the sizeof operator on
the object you are allocating, not on the type. For instance,
*don't* write this:

int *p = malloc (sizeof (int) * 128); /* Don't do this! */

Instead, write it this way:

int *p = malloc (sizeof *p * 128);

There's a few reasons to do it this way:

* If you ever change the type that `p' points to, it's not
necessary to change the malloc() call as well.
A better solution would be:

typedef int T;
T* p = (T*)malloc(128*sizeof(T));
This is more of a problem in a large program
but it's still convenient in a small one.

* Taking the size of an object makes writing the statement
less error-prone. You can verify that the sizeof syntax is
correct without having to look at the declaration.

Nov 13 '05 #10

P: n/a
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote in message
news:3F**************@jpl.nasa.gov...
Ben Pfaff wrote:
I don't recommend casting the return value of malloc():

* The cast is not required in ANSI C.
But an ANSI/ISO C++ compiler will complain.


So what? This is comp.lang.c.

* Casting its return value can mask a failure to
#include <stdlib.h>, which leads to undefined behavior.
No! It may mask the fact that malloc was not declared
but a good C compiler will warn you about that.


It might, but it's not required to. I'd rather rely upon
accurate knowledge than depend upon a convenience feature
of a tool, which might or might not exist.
* If you cast to the wrong type by accident,
odd failures can result.
Can you show us an example?


The OP's original message is a perfect example.
In fact, the second problem is your problem here. Fix it.

When calling malloc(), I recommend using the sizeof operator on
the object you are allocating, not on the type. For instance,
*don't* write this:

int *p = malloc (sizeof (int) * 128); /* Don't do this! */

Instead, write it this way:

int *p = malloc (sizeof *p * 128);

There's a few reasons to do it this way:

* If you ever change the type that `p' points to, it's not
necessary to change the malloc() call as well.


A better solution would be:

typedef int T;
T* p = (T*)malloc(128*sizeof(T));


Casting the return value from malloc() is never 'better'.
And your typdef only obfuscates things.
-Mike
Nov 13 '05 #11

P: n/a
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
Ben Pfaff wrote:
I don't recommend casting the return value of malloc():
* The cast is not required in ANSI C.


But an ANSI/ISO C++ compiler will complain.


Fortunately, we are not discussing C++. malloc() should not
normally be used in C++.
* Casting its return value can mask a failure to
#include <stdlib.h>, which leads to undefined behavior.


No! It may mask the fact that malloc was not declared
but a good C compiler will warn you about that.


This is in fact the OP's problem, so I don't see how you can
discount it.
* If you cast to the wrong type by accident,
odd failures can result.


Can you show us an example?


Casting to (char) instead of (char *) is bound to be a problem.
In fact, the second problem is your problem here. Fix it.
When calling malloc(), I recommend using the sizeof operator on
the object you are allocating, not on the type. For instance,
*don't* write this:
int *p = malloc (sizeof (int) * 128); /* Don't do this! */
Instead, write it this way:
int *p = malloc (sizeof *p * 128);
There's a few reasons to do it this way:
* If you ever change the type that `p' points to, it's not
necessary to change the malloc() call as well.


A better solution would be:

typedef int T;
T* p = (T*)malloc(128*sizeof(T));


I don't see how that's a better solution at all.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 13 '05 #12

P: n/a
"E. Robert Tisdale" wrote:

Ben Pfaff wrote:
I don't recommend casting the return value of malloc():

* The cast is not required in ANSI C.


But an ANSI/ISO C++ compiler will complain.


A COBOL compiler will complain even louder. So what?

--
Er*********@sun.com
Nov 13 '05 #13

P: n/a
On Mon, 01 Dec 2003 18:21:07 GMT, in comp.lang.c , Lionel Valero
<li***********@polymtl.ca> wrote:
Hello,

I have a test program that is compiled fine on a 32 bits redhat linux using gcc :
***********************
main (argc, argv)
int argc;
char *argv[];
{
int *ka;
int nka;

/* allocation dynamique entiere */
ka = (int *) malloc(nka * sizeof(int));


Everyone else has explained your immediate problem.forgetting

HoweverI notice you are using nka to size your array. But you didn't
initialise it to any value. So it contains garbage, and may crash your
program.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/ms3/bchambless0/welcome_to_clc.html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #14

P: n/a
Eric Sosman <Er*********@sun.com> scribbled the following:
"E. Robert Tisdale" wrote:
Ben Pfaff wrote:
> I don't recommend casting the return value of malloc():
>
> * The cast is not required in ANSI C.
But an ANSI/ISO C++ compiler will complain.

A COBOL compiler will complain even louder. So what?


ERT seems to have a fascination with compiling C code with a C++
compiler these days. Can you say "one-trick pony", ERT?

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
Nov 13 '05 #15

P: n/a
On Mon, 01 Dec 2003 13:07:09 -0800, "E. Robert Tisdale"
<E.**************@jpl.nasa.gov> wrote in comp.lang.c:
Lionel Valero wrote:
I have a test program
that is compiled fine on a 32 bits redhat linux using gcc :
***************
Still playing the fool I see, Tisdale.
> cat malloc.c #include <stdlib.h>
#include <stdio.h>

int main (int argc, char* argv[]) {
int nka = atoi(argv[1]);


What happens when you run it without command line arguments and
dereference the null pointer? Can you say "segfault"?
/* allocation dynamique entiere */
int* ka = (int*)malloc(nka*sizeof(int));
About one in 20 times you actually post something of value. Sadly,
this is not one of those times...

int *ka = malloc(nka * sizeof *ka);

Note the pleasing symmetry of the dual asterisks.
if (NULL == ka) {
fprintf(stderr, "<ERROR>: Out of free storage (malloc)!\n");
fprintf(stderr, "<ERROR>: %d int words required\n", nka);
exit (EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
> gcc -Wall -std=c99 -pedantic -o malloc malloc.c
> ./malloc 13
> ./malloc 999999999999

<ERROR>: Out of free storage (malloc)!
<ERROR>: 2147483647 int words required


Why didn't you show the results of running:

./malloc

???

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Nov 13 '05 #16

P: n/a
*** topposting fixed ***

Lionel Valero wrote:
Lionel Valero wrote:
I have a test program that is compiled fine on a 32 bits redhat linux
using gcc :
***********************
main (argc, argv)
int argc;
char *argv[];
Do not use old fashioned function declarations, they have been
obsolete for at least 15 years. main returns int, say so.
{
int *ka;
int nka;

/* allocation dynamique entiere */
ka = (int *) malloc(nka * sizeof(int));
Do not cast malloc results. nka is uninitialized. Use sizeof
*ka.
if (!ka) {
printf ("<ERROR> : Out of heap space (malloc) !\n");
printf ("<ERROR> : %d int words required\n", nka);
exit (-1);
-1 is not a portable value here. EXIT_FAILURE and
EXIT_SUCCESS come to mind, after #including <stdlib.h>
}
}
***********************

But under linux suse AMD opteron 64, i get this message from the compiler :

warning: cast to pointer from integer of different size

Any explanation ?

Increase the gcc warning levels. -W -Wall -ansi -pedantic -O1 are
the recommended minimum.

I forgto the headers :
#include <stdio.h>
#include <sys/types.h>
This is not a valid ISO C header. Omit it.
#include <time.h>


This is not used. omit it.

Please Do Not Toppost.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 13 '05 #17

P: n/a
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
Ben Pfaff wrote:
I don't recommend casting the return value of malloc():
* The cast is not required in ANSI C.


But an ANSI/ISO C++ compiler will complain.


So don't use a C++ compiler on C source (or a Fortran compiler, or an
Intercal compiler). There's no good reason C source code should be
constrained to be valid C++.

<OT>
Well-written C++ code doesn't use malloc() anyway; it uses the "new"
operator.
</OT>

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 13 '05 #18

P: n/a
On Mon, 01 Dec 2003 13:20:48 -0800, "E. Robert Tisdale"
<E.**************@jpl.nasa.gov> wrote:
Ben Pfaff wrote:
I don't recommend casting the return value of malloc():

* The cast is not required in ANSI C.


But an ANSI/ISO C++ compiler will complain.
* Casting its return value can mask a failure to
#include <stdlib.h>, which leads to undefined behavior.


No! It may mask the fact that malloc was not declared
but a good C compiler will warn you about that.


On a machine where the method of returning a pointer differs from the
method of returning an int (such as using a different register), the
behavior is indeed undefined. malloc will return the pointer using
the correct procedure. The compiler will generate code to convert the
assumed returned int. Since malloc did not return an int, this code
will operate on residual data.
<<Remove the del for email>>
Nov 13 '05 #19

P: n/a
Joona I Palaste <pa*****@cc.helsinki.fi> wrote:
Eric Sosman <Er*********@sun.com> scribbled the following:
"E. Robert Tisdale" wrote:
Ben Pfaff wrote:
> I don't recommend casting the return value of malloc():
>
> * The cast is not required in ANSI C.

But an ANSI/ISO C++ compiler will complain.

Which proves once again that C++ is broken, since the cast is useless
and useless casts should be anathema.
A COBOL compiler will complain even louder. So what?


ERT seems to have a fascination with compiling C code with a C++
compiler these days.


That's because ERT has, and AFAICT has always had, a bee in his bonnet
about C++ being "the new C". Not even Bjarne Stroustrup has that
delusion, but some people are impossible to disconfuse.

Richard
Nov 13 '05 #20

P: n/a
In <87************@pfaff.stanford.edu> Ben Pfaff <bl*@cs.stanford.edu> writes:
Instead, write it this way:

int *x = malloc (sizeof *x * 128);


Or, more readably:

int *x = malloc(128 * sizeof *x);

which tells to the human reader: I want to allocate space for 128 items
of that size.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #21

P: n/a
Lionel Valero <li***********@polymtl.ca> wrote:
I have a test program that is compiled fine on a 32 bits redhat linux using gcc :
***********************
main (argc, argv)
int argc;
char *argv[];
{
int *ka;
int nka;

/* allocation dynamique entiere */
ka = (int *) malloc(nka * sizeof(int));
if (!ka) {
printf ("<ERROR> : Out of heap space (malloc) !\n");
printf ("<ERROR> : %d int words required\n", nka);
exit (-1);
}
}
***********************

But under linux suse AMD opteron 64, i get this message from the compiler :

warning: cast to pointer from integer of different size

Any explanation ?


Well, the #include <...> headers that others have posted about will
fix the problem (the compiler thinks that malloc returns a 32bit int
because you didn't include a header file that says otherwise.)

But of course you have an additional problem that you did not define
the value of nka. Which is going to be another serious problem for
you to get the code working.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
Nov 13 '05 #22

P: n/a
Sorry,

this code is a peace of code taken from a bigger one, i should have instancied
nka value to make it clearer.

Paul Hsieh wrote:
Lionel Valero <li***********@polymtl.ca> wrote:
I have a test program that is compiled fine on a 32 bits redhat linux using gcc :
***********************
main (argc, argv)
int argc;
char *argv[];
{
int *ka;
int nka;

/* allocation dynamique entiere */
ka = (int *) malloc(nka * sizeof(int));
if (!ka) {
printf ("<ERROR> : Out of heap space (malloc) !\n");
printf ("<ERROR> : %d int words required\n", nka);
exit (-1);
}
}
***********************

But under linux suse AMD opteron 64, i get this message from the compiler :

warning: cast to pointer from integer of different size

Any explanation ?

Well, the #include <...> headers that others have posted about will
fix the problem (the compiler thinks that malloc returns a 32bit int
because you didn't include a header file that says otherwise.)

But of course you have an additional problem that you did not define
the value of nka. Which is going to be another serious problem for
you to get the code working.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/


--
-=O=------------------------------------------=O=-
Lionel Valéro
Analyste Informatique Département Génie Chimique
École Polytechnique de Montréal
C.P. 6079, succ. centre-ville
Montréal (Québec) H3C 3A7
Tel: (514) 340 - 4711 # 4805 / C552
Fax: (514) 340 - 4159
-=O=------------------------------------------=O=-
Nov 13 '05 #23

P: n/a
Barry Schwarz wrote:
On a machine where the method of returning a pointer
differs from the method of returning an int
(such as using a different register),
Please tell us which machine does this.
the behavior is indeed undefined.
malloc will return the pointer using the correct procedure.
The compiler will generate code to convert the assumed returned int.
Since malloc did not return an int,
this code will operate on residual data.


Could you please code up an example
and run it on the machine that you reference above
so that we can see how it fails?

Nov 13 '05 #24

P: n/a
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
Joona I Palaste <pa*****@cc.helsinki.fi> wrote:
Eric Sosman <Er*********@sun.com> scribbled the following:
"E. Robert Tisdale" wrote:
> Ben Pfaff wrote:
> > I don't recommend casting the return value of malloc():
> >
> > * The cast is not required in ANSI C.
>
> But an ANSI/ISO C++ compiler will complain.


Which proves once again that C++ is broken, since the cast is useless
and useless casts should be anathema.


<OT>
C++ is a different language than C, and there are valid reasons that
C++ disallows implicit conversions from void* to other pointer types.
These reasons don't apply to C. For details, see elsewhere.
</OT>

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 13 '05 #25

P: n/a
In <79**************************@posting.google.com > qe*@pobox.com (Paul Hsieh) writes:
Lionel Valero <li***********@polymtl.ca> wrote:
I have a test program that is compiled fine on a 32 bits redhat linux using gcc :
***********************
main (argc, argv)
int argc;
char *argv[];
{
int *ka;
int nka;

/* allocation dynamique entiere */
ka = (int *) malloc(nka * sizeof(int));
if (!ka) {
printf ("<ERROR> : Out of heap space (malloc) !\n");
printf ("<ERROR> : %d int words required\n", nka);
exit (-1);
}
}
***********************

But under linux suse AMD opteron 64, i get this message from the compiler :

warning: cast to pointer from integer of different size

Any explanation ?


Well, the #include <...> headers that others have posted about will
fix the problem (the compiler thinks that malloc returns a 32bit int
because you didn't include a header file that says otherwise.)

But of course you have an additional problem that you did not define
the value of nka. Which is going to be another serious problem for
you to get the code working.


I don't think that initialising nka is such a serious problem. Most
likely, this is the trimmed down version of his real program and he
trimmed too much.

What I find surprising is that, in this day and age, people still use
old style function definitions. Have they been asleep for the last 15
years or what?

And, while I can easily understand the usage of exit(1) to signal
failure (common convention under Unix and MSDOS), the usage of exit(-1)
keeps baffling me: I have yet to see a single implementation where the
value -1 is passed as such to the entity that launched the execution
of the program in question.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #26

P: n/a
In <3F**************@jpl.nasa.gov> "E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
Barry Schwarz wrote:
On a machine where the method of returning a pointer
differs from the method of returning an int
(such as using a different register),


Please tell us which machine does this.


The x86 in certain memory models, where an int is 16 bits and a pointer
is 32 bits.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #27

P: n/a
Dan Pop wrote:
E. Robert Tisdale writes:
Barry Schwarz wrote:
On a machine where the method of returning a pointer
differs from the method of returning an int
(such as using a different register),


Please tell us which machine does this.


The x86 in certain memory models
where an int is 16 bits and a pointer is 32 bits.


Could you please code up an example
and run it on the machine that you reference above
so that we can see how it fails?


Nov 13 '05 #28

P: n/a
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
Barry Schwarz wrote:
On a machine where the method of returning a pointer
differs from the method of returning an int
(such as using a different register),


Please tell us which machine does this.


One example is gcc on IA-64 Linux, which has 64-bit pointers and
32-bit ints. (It doesn't use a different register, but the size
mismatch causes similar problems.)
the behavior is indeed undefined.
malloc will return the pointer using the correct procedure.
The compiler will generate code to convert the assumed returned int.
Since malloc did not return an int,
this code will operate on residual data.


Could you please code up an example
and run it on the machine that you reference above
so that we can see how it fails?


I did this some time ago; search the archives.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 13 '05 #29

P: n/a
E. Robert Tisdale wrote:
Barry Schwarz wrote:
On a machine where the method of returning a pointer
differs from the method of returning an int
(such as using a different register),

Please tell us which machine does this.


Any machine where sizeof(int) is different than sizeof(char*) will do.

Though this is more OS or function calling convention dependent than
machine dependent.

-- glen

Nov 13 '05 #30

P: n/a
glen herrmannsfeldt <ga*@ugcs.caltech.edu> writes:
E. Robert Tisdale wrote:
Barry Schwarz wrote:
On a machine where the method of returning a pointer
differs from the method of returning an int
(such as using a different register),

Please tell us which machine does this.


Any machine where sizeof(int) is different than sizeof(char*) will do.

Though this is more OS or function calling convention dependent than
machine dependent.


Note that this (calling malloc() with no prototype) may happen to work
on some systems even if sizeof(int) > sizeof(void*). For example, if
int is 32 bits, void* is 64 bits, the value returned by malloc happens
to have the 32 high-order bits all zero, the machine is little-endian
(I think), and a few other unstated assumptions hold, you could
accidentally extract a valid 64-bit pointer from what the compiler
thinks is a 32-bit int result.

This is, of course, deep in the realm of undefined behavior. "Happens
to work" is actually a bad thing, because it can make it more
difficult to detect bugs. (Hey, maybe we should start referring to
this kind of thing as "HTW". 8-)})

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 13 '05 #31

P: n/a
[On mis-declaring malloc() and having code fail, in answer to
"where might this happen"]
Barry Schwarz wrote:
On a machine where the method of returning a pointer
differs from the method of returning an int
(such as using a different register),
E. Robert Tisdale wrote:
Please tell us which machine does this.

In article <nh7zb.6213$_M.26715@attbi_s54>,
glen herrmannsfeldt <ga*@ugcs.caltech.edu> wrote:Any machine where sizeof(int) is different than sizeof(char*) will do.

Though this is more OS or function calling convention dependent than
machine dependent.


Typically the function-call conventions mirror some properties of
the machine, though. Another example where it fails is some old
(Amiga, perhaps?) 680x0-based compilers, where pointer values are
returned in register A0 while integer values are returned in D0.

Amusingly enough, this entire thread resulted from using a machine
on which this occurred. The subject line -- "AMD opteron 64" --
names a machine that "does this", i.e., returns an int in a
different (sub)register than it returns pointers. This particular
AMD is being used in 64-bit mode, so that its "int"s are 32 bits
while its pointers are 64 bits.

The original poster failed to #include <stdlib.h>, then wrote a
call to malloc() that included a cast, and as a consequence, his
code compiled without diagnostics on one machine (32-bit x86) but
with a diagnostic on another (AMD in 64-bit mode). His question
was about the diagnostic. Had the O.P. avoided the cast -- as is
the usual comp.lang.c recommendation -- he would have gotten
diagnostics on both machines. Whether this would have led him to
the correct fix -- "#include <stdlib.h>" -- is not obvious, but it
would at least have elimininated one puzzling difference.

Although I do not have hard numbers, it is clear to me that,
statistically, many more people run into trouble by casting the
return value of malloc() than by not doing so. Casting malloc()
is a bit like smoking cigarettes: many will do so without ever
dying of lung cancer, but it is still a bad habit and a poor choice
of action.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 13 '05 #32

P: n/a
"E. Robert Tisdale" wrote:
Barry Schwarz wrote:
On a machine where the method of returning a pointer
differs from the method of returning an int
(such as using a different register),


Please tell us which machine does this.


Inasmuch as we try to write strictly portable code here, let us
conjugate some verbs:

I don't care We don't care
You don't care You (-all) don't care
He doesn't care They don't care
I am a Troll We are Trolls
You are a Troll You (-all) are Trolls
Trollsdale is a Troll Most Trollsdales are Trolls.

If you don't live in the southern US elide (-all). However,
looked on dispassionately, it serves a useful grammatical function
:-). I fail to find an equivalent use for ERT.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 13 '05 #33

P: n/a
In article <bq**********@elf.torek.net> Chris Torek <no****@torek.net> writes:
[On mis-declaring malloc() and having code fail, in answer to
"where might this happen"]
Barry Schwarz wrote:
On a machine where the method of returning a pointer
differs from the method of returning an int
(such as using a different register),
E. Robert Tisdale wrote:
Please tell us which machine does this.

.... Typically the function-call conventions mirror some properties of
the machine, though. Another example where it fails is some old
(Amiga, perhaps?) 680x0-based compilers, where pointer values are
returned in register A0 while integer values are returned in D0.


It was for certain on a Mac. Pointers in A0, integers in D0.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Nov 13 '05 #34

P: n/a
E. Robert Tisdale wrote:
Dan Pop wrote:
E. Robert Tisdale writes:
Barry Schwarz wrote:

On a machine where the method of returning a pointer
differs from the method of returning an int
(such as using a different register),
Please tell us which machine does this.

The x86 in certain memory models
where an int is 16 bits and a pointer is 32 bits.

Could you please code up an example
and run it on the machine that you reference above
so that we can see how it fails?


How lazy can you get?

Nov 13 '05 #35

P: n/a
In <3F************@jpl.nasa.gov> "E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
Dan Pop wrote:
E. Robert Tisdale writes:
Barry Schwarz wrote:

On a machine where the method of returning a pointer
differs from the method of returning an int
(such as using a different register),

Please tell us which machine does this.


The x86 in certain memory models
where an int is 16 bits and a pointer is 32 bits.


Could you please code up an example
and run it on the machine that you reference above
so that we can see how it fails?


Yes, I can, but it shouldn't be necessary: only an idiot couldn't
figure out how it fails.

H:\>type good.c
#include <stdio.h>
#include <stdlib.h>

int main()
{
char *p = malloc(10);
printf("%p\n", (void *)p);
return 0;
}

H:\>tcc -mh good.c
Turbo C++ Version 1.01 Copyright (c) 1990 Borland International
good.c:
Turbo Link Version 3.01 Copyright (c) 1987, 1990 Borland International

Available memory 410832

H:\>good
0856:0004

H:\>type bad.c
#include <stdio.h>

int main()
{
char *p = (char *)malloc(10);
printf("%p\n", (void *)p);
return 0;
}

H:\>tcc -mh bad.c
Turbo C++ Version 1.01 Copyright (c) 1990 Borland International
bad.c:
Turbo Link Version 3.01 Copyright (c) 1987, 1990 Borland International

Available memory 418000

H:\>bad
0000:0004

The address printed by the bad program is right into the interrupt
vector area of the processor, therefore it is clearly not the address
returned by malloc. If the bad program actually attempted to write
something into it, the whole system would get screwed.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #36

P: n/a
Dan Pop wrote:
E. Robert Tisdale writes:
Dan Pop wrote:
E. Robert Tisdale writes:

Barry Schwarz wrote:

>On a machine where the method of returning a pointer
>differs from the method of returning an int
>(such as using a different register),

Please tell us which machine does this.

The x86 in certain memory models
where an int is 16 bits and a pointer is 32 bits.


Could you please code up an example
and run it on the machine that you reference above
so that we can see how it fails?


Yes, I can, but it shouldn't be necessary: only an idiot couldn't
figure out how it fails.

H:\>type good.c
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {
char *p = malloc(10);
printf("%p\n", (void *)p);
return 0;
}

H:\>tcc -mh good.c
Turbo C++ Version 1.01 Copyright (c) 1990 Borland International
good.c:
Turbo Link Version 3.01 Copyright (c) 1987, 1990 Borland International

Available memory 410832

H:\>good
0856:0004

H:\>type bad.c
#include <stdio.h>

int main(int argc, char* argv[]) {
char *p = (char *)malloc(10);
printf("%p\n", (void *)p);
return 0;
}

H:\>tcc -mh bad.c
Turbo C++ Version 1.01 Copyright (c) 1990 Borland International
bad.c:
Turbo Link Version 3.01 Copyright (c) 1987, 1990 Borland International

Available memory 418000

H:\>bad
0000:0004

The address printed by the bad program
is right into the interrupt vector area of the processor,
therefore it is clearly not the address returned by malloc.
If the bad program actually attempted to write something into it,
the whole system would get screwed.


Thanks Dan. I knew you could do it.

The only problem is that your example is for a C++ compiler (Turbo C++)
which is obsolete, which never fully complied
with the ANSI/ISO C89 standard much less the ANSI/ISO C99 standard
and which was designed to emit code for Intel 80286 processors.
There are almost no C programmers who actually consider it
a viable target for their applications -- nobody cares.

The point is that

1. a good C compiler will warn the programmer
if malloc has not been declared properly and
2. the code will probably execute properly
even if malloc has not been declared properly.

Omitting the type cast for the result returned by malloc
does *nothing* for the programmer except to produce
a cryptic and, possibly, misleading diagnostic
when malloc has not been declared properly.

Nov 13 '05 #37

P: n/a
"E. Robert Tisdale" wrote:

Thanks Dan. I knew you could do it.

The only problem is that your example is for a C++ compiler (Turbo C++)
which is obsolete, which never fully complied
with the ANSI/ISO C89 standard much less the ANSI/ISO C99 standard
and which was designed to emit code for Intel 80286 processors.
There are almost no C programmers who actually consider it
a viable target for their applications -- nobody cares.
Awfully critical of work someone else did at your
request and without reward ...
The point is that

1. a good C compiler will warn the programmer
if malloc has not been declared properly and
True. In fact, a C99-conforming compiler *must*
complain if malloc() or any other function is used
without a prior declaration.
2. the code will probably execute properly
even if malloc has not been declared properly.
False, as Dan's example demonstrated. False, false,
false. What part of "false" are you having trouble with?
Omitting the type cast for the result returned by malloc
does *nothing* for the programmer except to produce
a cryptic and, possibly, misleading diagnostic
when malloc has not been declared properly.


A cryptic and possibly misleading diagnostic is more
helpful than no diagnostic at all. In fact, this entire
thread stems from an incident in which the unnecessary
cast hid the diagnostic the compiler would otherwise
have been required to produce! The O.P.'s mistake in
omitting <stdlib.h> went unnoticed, exactly as we've all
said would happen.

So omitting the cast is demonstrably helpful, with
this thread as the demonstration. What benefit does
*inserting* the unnecessary cast provide? None! None,
none, none. What part of "none" are you having trouble
with?

Y'know, if one cast is good, perhaps more would be
even better:

struct foo *p = (struct foo *)(uintptr_t)(const void *)
(intptr_t)(char **)malloc((size_t)sizeof(struct foo));
if (0 != ((p == (struct foo*)NULL) == (int)1)) {
(void)perror ((const char*)"malloc failed!");
(void)exit ((int)EXIT_FAILURE);
}

--
Er*********@sun.com
Nov 13 '05 #38

P: n/a
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
[snip]
Thanks Dan. I knew you could do it.

The only problem is that your example is for a C++ compiler (Turbo C++)
which is obsolete, which never fully complied
with the ANSI/ISO C89 standard much less the ANSI/ISO C99 standard
and which was designed to emit code for Intel 80286 processors.
There are almost no C programmers who actually consider it
a viable target for their applications -- nobody cares.


As I mentioned in this thread, I posted an example myself (for gcc
under IA-64 Linux) some time ago. Since you seem disinclined to
search for it yourself, here's the Google Groups URL:

http://groups.google.com/gr*********...***@cts.com%3E

I posted it about 6 weeks ago in the "why still use C?" thread. You
may have missed it the first time around; I see that you didn't
participate in the thread after that.

And of course the article that started this thread was yet another
perfectly valid example of the problem you keep telling us nobody
cares about.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 13 '05 #39

P: n/a
Eric Sosman <Er*********@sun.com> writes:
"E. Robert Tisdale" wrote:
2. the code will probably execute properly
even if malloc has not been declared properly.


False, as Dan's example demonstrated. False, false,
false. What part of "false" are you having trouble with?


Why are you arguing with a troll? This is ERT's modus operandi:
he makes an incorrect statement and when people show that he is
wrong, he denies their evidence. Don't bothe
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 13 '05 #40

P: n/a
Eric Sosman wrote:
A cryptic and possibly misleading diagnostic
is more helpful than no diagnostic at all.
In fact, this entire thread stems from an incident
in which the unnecessary cast hid the diagnostic
that the compiler would otherwise have been required to produce!
The O.P.'s mistake in omitting [the declaration of malloc]
went unnoticed exactly as we've all said would happen.
You are confused. No diagnostic was hidden.
You need to reread Lionel Valéro's original post.
The diagnostic message was,
"warning: cast to pointer from integer of different size".
It says nothing about the fact that malloc was not declared.
It certainly doesn't tell you that stdlib.h was not included.
My GNU C compiler
gcc --version gcc (GCC) 3.2 20020903 (Red Hat Linux 8.0 3.2-7)

issues a more informative diagnostic message:

malloc.c:8: warning: implicit declaration of function `malloc'

The solution to this problem is to get a better C compiler
and *not* to cobble your code to accommodate inferior C compilers.
What benefit does *inserting* the cast provide?


It allows you to compile your code with a C++ compiler.
This is important because it allows your C code to survive
even if the C language itself doesn't survive.

Nov 13 '05 #41

P: n/a
Keith Thompson wrote:


As I mentioned in this thread, I posted an example myself (for gcc
under IA-64 Linux) some time ago. Since you seem disinclined to
search for it yourself, here's the Google Groups URL:

http://groups.google.com/gr*********...***@cts.com%3E

I posted it about 6 weeks ago in the "why still use C?" thread. You
may have missed it the first time around; I see that you didn't
participate in the thread after that.

And of course the article that started this thread was yet another
perfectly valid example of the problem you keep telling us nobody
cares about.

I just happen to have access to an IA-64 Linux machine:
expand main.c #include <stdio.h>

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

printf("sizeof(int) = %d\n", (int)sizeof(int));
printf("sizeof(void*) = %d\n", (int)sizeof(void*));

int* p = (int*)malloc(sizeof(int));
printf("p = [%p]\n", (void*)p);
fflush(stdout);

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

return 0;
}
ecc -Wall -std=c99 -o main main.c

main.c(8): warning #266: function declared implicitly
int* p = (int*)malloc(sizeof(int));
^

main.c(8): remark #967: conversion from "int" to "int *";
sizes do not match
int* p = (int*)malloc(sizeof(int));
^

A good C compiler will warn you about this problem
whether or not you use a cast.

Nov 13 '05 #42

P: n/a
"E. Robert Tisdale" wrote:

Eric Sosman wrote:
A cryptic and possibly misleading diagnostic
is more helpful than no diagnostic at all.
In fact, this entire thread stems from an incident
in which the unnecessary cast hid the diagnostic
that the compiler would otherwise have been required to produce!
The O.P.'s mistake in omitting [the declaration of malloc]
went unnoticed exactly as we've all said would happen.
You are confused. No diagnostic was hidden.
You need to reread Lionel Valéro's original post.
The diagnostic message was,
"warning: cast to pointer from integer of different size".


No, the confusion is elsewhere. The O.P. asked why his
program compiled without complaint in one environment and
elicited a diagnostic on another. Without the cast, the
program would have produced diagnostics on *all* C compilers.
Thus, the cast hid the required diagnostic, and it was pure
luck that an "optional" or "extraneous" diagnostic from another
compiler drew his attention to the error.
It says nothing about the fact that malloc was not declared.
It certainly doesn't tell you that stdlib.h was not included.
Nor does it tell you how to feed the hungry, heal the sick,
and end war. And when the diagnostic is suppressed altogether,
as in the O.P.'s original environment, it doesn't even tell
you to come in out of the rain.

But if the diagnostic had been permitted to appear, it
would at least have alerted the O.P. to the existence of a
problem. The description of the problem might not have been
all that could be desired, but knowing that a problem exists
is at least half the battle in finding the cure.
My GNU C compiler
> gcc --version gcc (GCC) 3.2 20020903 (Red Hat Linux 8.0 3.2-7)

issues a more informative diagnostic message:

malloc.c:8: warning: implicit declaration of function `malloc'


That's nice. Seriously, it *is* nice. So what?
The solution to this problem is to get a better C compiler
and *not* to cobble your code to accommodate inferior C compilers.


The "inferior compilers" in the O.P.'s case were (ahem)
gcc and gcc. And I fail to see how leaving out an unnecessary
and potentially harmful cast constitutes "cobbling" the code.
What benefit does *inserting* the cast provide?


It allows you to compile your code with a C++ compiler.
This is important because it allows your C code to survive
even if the C language itself doesn't survive.


I once saw a cute little "Hello, world!" program that
ran correctly in three different languages: C, Fortran, and sh,
if I recall aright. It was an amusing stunt, but hardly a useful
way to write programs ...

I put it to you that writing programs that are somehow
simultaneously both C and C++ is an exercise of similar
[f]utility. Yes, it's possible to write such code, if one
is willing to wear a tight enough strait jacket. But the
result will be derided by both camps: Neither the C people
nor the C++ people will deem it good code. In the particular
case of malloc(), the C++ folks will say it's poor practice
to use it in the first place; the `new' operator needs no
cast. If you want to write C++ go right ahead and do so --
but don't pretend that writing bad C code so it can masquerade
as bad C++ code is a good idea.

Personally, I use `new' as an identifier whenever I can
find a reasonable excuse to do so.

--
Er*********@sun.com
Nov 13 '05 #43

P: n/a
Ben Pfaff wrote:

Eric Sosman <Er*********@sun.com> writes:
"E. Robert Tisdale" wrote:
2. the code will probably execute properly
even if malloc has not been declared properly.


False, as Dan's example demonstrated. False, false,
false. What part of "false" are you having trouble with?


Why are you arguing with a troll?


Because he writes with an authoritative manner, and people
might therefore believe he's an authority. I have observed
that he oscillates between nonsense on some threads and good
advice on others; the latter tends to build credibility for
the former. (And makes it not entirely proper to dismiss
him as purely a troll; sometimes he *does* make sense.)

Somebody's got to contradict him when he spouts foolishness.
I'm not volunteering to be Permanent Latrine Orderly, so it's
kind of a coin-toss whether I'll join in on a thread or just
leave his flagellation to others -- there never seems to be a
shortage of people willing to point out misteaks, and in the
case of ERT I think that's a good thing.

I just wish I knew whether he does it out of forgivable
ignorance or out of malice.

--
Er*********@sun.com
Nov 13 '05 #44

P: n/a
Eric Sosman wrote:
If you want to write C++ go right ahead and do so --
but don't pretend that writing bad C code so it can masquerade
as bad C++ code is a good idea.
Amen...
Personally, I use `new' as an identifier whenever I can
find a reasonable excuse to do so.


Yes, and this is not through anti-C++ bloodymindedness. All right - it's not
/just/ through anti-C++ bloodymindedness. There's a much more important
reason, too: it's a heads-up to anyone compiling the code with a C++
compiler; a message from the original author. When translated, the message
reads "I wrote this in C. I have assumed C rules throughout. C++ is
different from C. Proof: the diagnostic you are now reading! So either
rewrite this from the ground up in C++, or leave it alone".

Not bad for three letters. :-)

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #45

P: n/a
Eric Sosman wrote:

The "inferior compilers" in the O.P.'s case
were (ahem) gcc and gcc.
No. Lionel Valéro simply forgot to use
the appropriate options (-Wall, etc.)
I put it to you that writing programs that are somehow
simultaneously both C and C++ is an exercise of [f]utility.
Yes, it's possible to write such code
if one is willing to wear a tight enough strait jacket.
But the result will be derided by both camps:
Neither the C people nor the C++ people will deem it good code.
In the particular case of malloc(), the C++ folks will say
it's poor practice to use it in the first place;
the `new' operator needs no cast.
If you want to write C++ go right ahead and do so --
but don't pretend that writing bad C code
so it can masquerade as bad C++ code is a good idea.
If I find a great open source function library implemented in C,
a I obliged to re-implement in C++ so that "C++ folks"
will "deem it good code"? I don't think so.
I just compile it with my C++ compiler
and link it into my C++ programs.
Personally, I use `new' as an identifier
whenever I can find a reasonable excuse to do so.


Just to frustrate C++ programmers?
Is your code really more valuable
if C++ programmers can't use it?
Does your employer/client know that you do this?

Nov 13 '05 #46

P: n/a
E. Robert Tisdale wrote:
Eric Sosman wrote:
If you want to write C++ go right ahead and do so --
but don't pretend that writing bad C code
so it can masquerade as bad C++ code is a good idea.
If I find a great open source function library implemented in C,
a I obliged to re-implement in C++ so that "C++ folks"
will "deem it good code"? I don't think so.


Right. You can just link it in, and everyone's happy.
I just compile it with my C++ compiler
and link it into my C++ programs.
Right.
Personally, I use `new' as an identifier
whenever I can find a reasonable excuse to do so.


Just to frustrate C++ programmers?


No, not just for that. Partly to warn them "this is C code - compile as C,
then link".
Is your code really more valuable
if C++ programmers can't use it?
But they can, as you yourself just pointed out!
Does your employer/client know that you do this?


I'm sure Eric Sosman's employer knows perfectly well that Eric is a
programmer to be trusted.

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 13 '05 #47

P: n/a
The Real OS/2 Guy wrote:
On Mon, 1 Dec 2003 19:00:18 UTC, Lionel Valero
<li***********@polymtl.ca> wrote:

I forgto the headers :
#include <stdio.h>
#include <sys/types.h>
#include <time.h>


You forgot to include stdlib.h again
Lionel Valero wrote:


ka = (int *) malloc(nka * sizeof(int));

And this cast hides the error that you forgot to include the header in
redhat linux.
Casting the result from a function that returns void* is always an
error.


Well, I wouldn't go that far. Consider replacing the first occurrence
of 'a' with 'A" in a block of 100 bytes, given that it exists.

*(char*)memchr(buffer, 'a', sizeof buffer) = 'A';

seems like a reasonable solution.

Nov 13 '05 #48

P: n/a
In <3F**************@jpl.nasa.gov> "E. Robert Tisdale" <E.**************@jpl.nasa.gov> writes:
Dan Pop wrote:
E. Robert Tisdale writes:
Dan Pop wrote:

E. Robert Tisdale writes:

>Barry Schwarz wrote:
>
>>On a machine where the method of returning a pointer
>>differs from the method of returning an int
>>(such as using a different register),
>
>Please tell us which machine does this.

The x86 in certain memory models
where an int is 16 bits and a pointer is 32 bits.

Could you please code up an example
and run it on the machine that you reference above
so that we can see how it fails?


Yes, I can, but it shouldn't be necessary: only an idiot couldn't
figure out how it fails.

H:\>type good.c
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {
char *p = malloc(10);
printf("%p\n", (void *)p);
return 0;
}

H:\>tcc -mh good.c
Turbo C++ Version 1.01 Copyright (c) 1990 Borland International
good.c:
Turbo Link Version 3.01 Copyright (c) 1987, 1990 Borland International

Available memory 410832

H:\>good
0856:0004

H:\>type bad.c
#include <stdio.h>

int main(int argc, char* argv[]) {
char *p = (char *)malloc(10);
printf("%p\n", (void *)p);
return 0;
}

H:\>tcc -mh bad.c
Turbo C++ Version 1.01 Copyright (c) 1990 Borland International
bad.c:
Turbo Link Version 3.01 Copyright (c) 1987, 1990 Borland International

Available memory 418000

H:\>bad
0000:0004

The address printed by the bad program
is right into the interrupt vector area of the processor,
therefore it is clearly not the address returned by malloc.
If the bad program actually attempted to write something into it,
the whole system would get screwed.


Thanks Dan. I knew you could do it.

The only problem is that your example is for a C++ compiler (Turbo C++)
which is obsolete, which never fully complied
with the ANSI/ISO C89 standard much less the ANSI/ISO C99 standard
and which was designed to emit code for Intel 80286 processors.


Wrong. The code is for a C compiler that does conform with the
ANSI/ISO C89 standard. The lack of a diagnostic for good.c is the
ultimate proof that the compiler was used as a C compiler and not as a
C++ compiler.

Nothing in your initial request outruled Intel 80286 processors, or
conforming C89 implementations, therefore my example is an adequate
response to your request.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 13 '05 #49

P: n/a
Richard Heathfield wrote:
E. Robert Tisdale wrote:
.... snip ...
Does your employer/client know that you do this?


I'm sure Eric Sosman's employer knows perfectly well that Eric
is a programmer to be trusted.


A more germane question is "Does ERTs employer know what he does
here?". If his job is pushing a broom it probably doesn't matter.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 13 '05 #50

54 Replies

This discussion thread is closed

Replies have been disabled for this discussion.