473,383 Members | 1,859 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Help with warning when using calloc/malloc

MK
I am a newbie. Please help. The following warning is issued by gcc-3.2.2
compiler (pc Linux):
================================================== ================
read_raw_data.c:51: warning: assignment makes pointer from integer
without a cast
================================================== ================

when the following piece of code was compiled. The offending statement
is calloc. A similar statement in the main() function passes without any
warning. Am I allowed to use calloc (and malloc) only within main() or
am I doing something very silly ??
=============================================
init(char *file, double *grid, \
double *start){
double *depth;
int pts
depth = calloc(pts,sizeof (double));

}
============================================

Thanks.

MK

Nov 14 '05 #1
27 4696

"MK" <ms***@yahoo.co.uk> wrote in message
news:c0**********@aspen.sucs.soton.ac.uk...
I am a newbie. Please help. The following warning is issued by gcc-3.2.2
compiler (pc Linux):
================================================== ================
read_raw_data.c:51: warning: assignment makes pointer from integer
without a cast
================================================== ================

when the following piece of code was compiled. The offending statement
is calloc. A similar statement in the main() function passes without any
warning. Am I allowed to use calloc (and malloc) only within main() or
am I doing something very silly ??
=============================================
init(char *file, double *grid, \
double *start){
double *depth;
int pts
depth = calloc(pts,sizeof (double));

}


Did you include stdlib.h?

Tom
Nov 14 '05 #2
MK,

1. You are not initialising pts with a value
2. You should cast the (void *) returned from calloc to (double *)
3. When declaring pointers it's a good idea to initialise them to NULL to
start with (memory functions like free() will ignore NULL's)

Try the following instead...

init(char *file, double *grid, double *start) {
double *depth = NULL; /* It's always a good idea to initialise ALL
pointers to NULL */
int pts = 5; /* We need ptr to be initialise with a value */
depth = (double *) calloc(pts,sizeof (double)); /* We really should cast
the result to a (double *) */
}

I haven't tried this code on GCC but it compiles fine in VS2003.

Good luck.

"MK" <ms***@yahoo.co.uk> wrote in message
news:c0**********@aspen.sucs.soton.ac.uk...
I am a newbie. Please help. The following warning is issued by gcc-3.2.2
compiler (pc Linux):
================================================== ================
read_raw_data.c:51: warning: assignment makes pointer from integer
without a cast
================================================== ================

when the following piece of code was compiled. The offending statement
is calloc. A similar statement in the main() function passes without any
warning. Am I allowed to use calloc (and malloc) only within main() or
am I doing something very silly ??
=============================================
init(char *file, double *grid, \
double *start){
double *depth;
int pts
depth = calloc(pts,sizeof (double));

}
============================================

Thanks.

MK

Nov 14 '05 #3

"Ricky Cormier" <evilrix@[@@@]hotmail.com> wrote in message
news:K7**************@newsfep3-gui.server.ntli.net...
MK,

1. You are not initialising pts with a value
2. You should cast the (void *) returned from calloc to (double *)
No, no no no no. That hides bugs and is just not required.
3. When declaring pointers it's a good idea to initialise them to NULL to
start with (memory functions like free() will ignore NULL's)


This is retarded. First off, on error they will return NULL anyways.

Second where are my taquitos!

Tom
Nov 14 '05 #4
MK
No I didn't and that was the problem.
Thank you very much for your help Tom.
MK
Tom St Denis wrote:
"MK" <ms***@yahoo.co.uk> wrote in message
news:c0**********@aspen.sucs.soton.ac.uk...
I am a newbie. Please help. The following warning is issued by gcc-3.2.2
compiler (pc Linux):
================================================ ==================
read_raw_data.c:51: warning: assignment makes pointer from integer
without a cast
================================================ ==================

when the following piece of code was compiled. The offending statement
is calloc. A similar statement in the main() function passes without any
warning. Am I allowed to use calloc (and malloc) only within main() or
am I doing something very silly ??
=============================================
init(char *file, double *grid, \
double *start){
double *depth;
int pts
depth = calloc(pts,sizeof (double));

}

Did you include stdlib.h?

Tom


Nov 14 '05 #5
On Thu, 12 Feb 2004 15:06:13 +0000, MK wrote:
I am a newbie. Please help. The following warning is issued by gcc-3.2.2
compiler (pc Linux):
================================================== ================
read_raw_data.c:51: warning: assignment makes pointer from integer
without a cast
================================================== ================

when the following piece of code was compiled. The offending statement
is calloc. A similar statement in the main() function passes without any
warning. Am I allowed to use calloc (and malloc) only within main() or
am I doing something very silly ??
There seem to be some errors, i'll put ^^^ under them.
=============================================
init(char *file, ^^^^
You probably mean "int". But you might want "void" instead (as this
function seems to not return anything, otherwise do return an int).
double *grid, \ ^^^
This seems like an escape from the newline - such as seen in Unix
shell-script, no need for that in C, here "carriage return" is just
whitespace like tab or space are.
double *start){
double *depth;
int pts ^^^
Forgot the ";" there...
depth = calloc(pts,sizeof (double));

}
============================================

Thanks.


The rest seems fine. Exept that it takes some arguments, which are unused.
However this snipped may only be "part of" the actual function?

--
-Menno.

Nov 14 '05 #6
"Ricky Cormier" <evilrix@[@@@]hotmail.com> wrote:

[ Do not top-post! ]
"MK" <ms***@yahoo.co.uk> wrote in message
news:c0**********@aspen.sucs.soton.ac.uk...
read_raw_data.c:51: warning: assignment makes pointer from integer
without a cast init(char *file, double *grid, \
double *start){

double *depth;
int pts
depth = calloc(pts,sizeof (double));

}

1. You are not initialising pts with a value
Not only that, but there's no semicolon on that line.
2. You should cast the (void *) returned from calloc to (double *)
*No* *you* *should* *not*!

This comes up every week or so. malloc() and related functions should
_not_ need the cast in well-written C code. I'm not even going to
enumerate all the reasons why not, ask Google Groups if you want to gain
some wisdom.

What you _should_ do, however, is include the proper header for every
function you use. In this case,

#include <stdlib.h>

Also, using sizeof *pointer instead of sizeof(fixedtype) in allocation
calls makes for more solid code.
3. When declaring pointers it's a good idea to initialise them to NULL to
start with (memory functions like free() will ignore NULL's)
Rarely. Do you initialise all your integers to 0 before assigning a
different value to them? No? Then why treat pointers differently?
Try the following instead...

init(char *file, double *grid, double *start) {
double *depth = NULL; /* It's always a good idea to initialise ALL
pointers to NULL */
int pts = 5; /* We need ptr to be initialise with a value */
depth = (double *) calloc(pts,sizeof (double)); /* We really should cast
the result to a (double *) */
}
Or rather, do this:

/* Put this line somewhere before you first use calloc(),
typically at the start of the file: */
#include <stdlib.h>

/* Implicit int went out with C99, and was never a good idea to begin
with. Use an explicit return type, or void. */
int init(char *file, double *grid, double *start)
{
double *depth;
int pts;

/* Place code here that gives pts a value, or at a pinch, but rather
not, initialise it with a fixed value using, e.g., int pts=10; */
depth = calloc(pts, sizeof *depth);

/* Use depth for something. */

/* And don't forget, somewhere where depth is still is scope, to: */
free(depth);

return some_value;
}
I haven't tried this code on GCC but it compiles fine in VS2003.


Code that works by accident is dangerous code. Hitch up the optimisation
level and it _might_ just crash on you.

Richard
Nov 14 '05 #7
Menno Duursma <me***@desktop.lan> wrote:
On Thu, 12 Feb 2004 15:06:13 +0000, MK wrote:
=============================================
init(char *file, ^^^^
You probably mean "int".


Erm... then what's the function called?
double *grid, \

^^^
This seems like an escape from the newline - such as seen in Unix
shell-script, no need for that in C, here "carriage return" is just
whitespace like tab or space are.


No need, true, but perfectly legal C. In fact, in some cases it _is_
necessary - AFAIK, since adjacent string literals started to
concatenate, it's only been needed for multi-line macro definitions, but
in that case, it's the only real solution.
The rest seems fine. Exept that it takes some arguments, which are unused.


And that the actual problem is elsewhere.

Richard
Nov 14 '05 #8
Tom St Denis wrote:

"Ricky Cormier" <evilrix@[@@@]hotmail.com> wrote in message
news:K7**************@newsfep3-gui.server.ntli.net...

3. When declaring pointers it's a good idea to initialise
them to NULL to start with (memory functions like free()
will ignore NULL's)


This is retarded.
First off, on error they will return NULL anyways.


I don't think so.
void free(void *ptr);

--
pete
Nov 14 '05 #9

"pete" <pf*****@mindspring.com> wrote in message
news:40***********@mindspring.com...
Tom St Denis wrote:

"Ricky Cormier" <evilrix@[@@@]hotmail.com> wrote in message
news:K7**************@newsfep3-gui.server.ntli.net...

3. When declaring pointers it's a good idea to initialise
them to NULL to start with (memory functions like free()
will ignore NULL's)


This is retarded.
First off, on error they will return NULL anyways.


I don't think so.
void free(void *ptr);


I meant calloc/malloc.

Stop being such a smacktard already.

Tom
Nov 14 '05 #10
Ricky Cormier wrote:
[a top-post, here corrected]

"MK" <ms***@yahoo.co.uk> wrote in message
news:c0**********@aspen.sucs.soton.ac.uk...
I am a newbie. Please help. The following warning is issued by gcc-3.2.2
compiler (pc Linux):
================================================== ================
read_raw_data.c:51: warning: assignment makes pointer from integer
without a cast
================================================== ================

when the following piece of code was compiled. The offending statement
is calloc. A similar statement in the main() function passes without any
warning. Am I allowed to use calloc (and malloc) only within main() or
am I doing something very silly ??
=============================================
init(char *file, double *grid, \
double *start){
double *depth;
int pts
depth = calloc(pts,sizeof (double));

}
[...]
1. You are not initialising pts with a value


Irrelevant, since `pts' is not being used. The lack
of a trailing semicolon, however, would be troublesome ...
2. You should cast the (void *) returned from calloc to (double *)
No, NO, NO-NO-NO! Had he followed this bad advice, he
would probably not have received the error message. Silencing
the message without curing the error is a poor idea. It's the
appearance of the message that prompted MK to consult this forum;
if he had not been warned of a problem he'd most likely never
have learned how to correct it.
3. When declaring pointers it's a good idea to initialise them to NULL to
start with (memory functions like free() will ignore NULL's)


The parenthetical remark is correct, but the rest of the
sentence is wrong-headed or even foolhardy. One important
disadvantage of the practice is that it prevents the compiler
from diagnosing the use of an uninitialized variable (if the
compiler has that ability). For example,

char *ptr;
switch (state) {
case 0:
ptr = "California";
break;
case 1:
ptr = "Siberia";
break;
}
printf ("You have been exiled to %s\n", ptr);

A helpful compiler will warn you that `ptr' may not have
been initialized by the time the printf() call is executed,
because no assignment will occur if `state' has a value
like, say, 42. A careful programmer will pay heed to the
warning and examine what possible values `state' may hold,
and might perhaps decide to use something other than a
`switch' to inspect the value.

However, if you wrote `char *ptr = NULL;' as recommended
by Mr. Cormier, the compiler would not detect the problem:
`ptr' has been initialized, albeit with a useless value.
Then if `state' is 42, you'll wind up executing

printf ("You have been exiled to %s\n", (char*)NULL);

Every software maintenance study I've ever read has found
that the cost of a bug rises with the amount of time it lives
in the code. Hence, earlier detection leads to lower cost,
so it's to your advantage *not* to suppress helpful warnings.

--
Er*********@sun.com
Nov 14 '05 #11
On Thu, 12 Feb 2004 16:25:39 +0000, Richard Bos wrote:
Menno Duursma <me***@desktop.lan> wrote:
On Thu, 12 Feb 2004 15:06:13 +0000, MK wrote:
> =============================================
> init(char *file,

^^^^
You probably mean "int".


Erm... then what's the function called?


Oops. Your right, thanks. What i ment here, somthing like:

int some_func( ... )
{
...
return some_int;
}

[ Snip. ]
The rest seems fine. Exept that it takes some arguments, which are unused.


And that the actual problem is elsewhere.


Well, i'm surprised calling calloc() from main() _did_ work for the OP,
without haveing included stdlib.h ... Using "-Wall" with gcc 3.2.3 i get:

calloc_test.c: In function `main':
calloc_test.c:6: warning: implicit declaration of function `calloc'

But maybe i shouldn't have assumed any compiler will do that ...

--
-Menno.

Nov 14 '05 #12
Tom St Denis wrote:

"pete" <pf*****@mindspring.com> wrote in message
news:40***********@mindspring.com...
Tom St Denis wrote:

"Ricky Cormier" <evilrix@[@@@]hotmail.com> wrote in message
news:K7**************@newsfep3-gui.server.ntli.net...
> 3. When declaring pointers it's a good idea to initialise
> them to NULL to start with (memory functions like free()
> will ignore NULL's)

This is retarded.
First off, on error they will return NULL anyways.


I don't think so.
void free(void *ptr);


I meant calloc/malloc.


Your original statement was merely wrong.
Your corrected statement,
has nothing to do with the post that you replied to.
Stop being such a smacktard already.


--
pete
Nov 14 '05 #13
Menno Duursma wrote:
Well, i'm surprised calling calloc() from main() _did_ work for the OP,
without haveing included stdlib.h ... Using "-Wall" with gcc 3.2.3 i get:

calloc_test.c: In function `main':
calloc_test.c:6: warning: implicit declaration of function `calloc'
That's a feature offered by some compilers, but it is not a required
diagostic.
But maybe i shouldn't have assumed any compiler will do that ...


Wow, you are already more clueful than E.R. Tisdale. Excellent!


Brian Rodenborn
Nov 14 '05 #14
"Tom St Denis" <to*@securescience.net> wrote in message
news:Nc******************@twister01.bloor.is.net.c able.rogers.com...

"Ricky Cormier" <evilrix@[@@@]hotmail.com> wrote in message
news:K7**************@newsfep3-gui.server.ntli.net...
MK,

1. You are not initialising pts with a value
2. You should cast the (void *) returned from calloc to (double *)
No, no no no no. That hides bugs and is just not required.


It is good practice (read elsewhere in this group for the various arguments
made by others far more qualified than me) to do this. Notice I said
'should' and not 'must'! Just out of interest, what bugs will it hide? Good
programming practice suggests it is always a good idea to be explicit when
coding rather than implicit (such as in this case an explicit cast rather
than an implicit one).
3. When declaring pointers it's a good idea to initialise them to NULL to start with (memory functions like free() will ignore NULL's)
This is retarded. First off, on error they will return NULL anyways.


I'm sorry you feel this is retarded. However, it is a good idea to
initialise ANY variable - including pointers! In the case of pointers it's
common practice to use NULL. By initialising the pointer to NULL we have a
guarenteed value to test for. I accept your premise that c/malloc will
return NULL if the call fails (I never claimed otherwise) but what if the
programmer was daft enough to forget to call c/malloc (it could happen) and
we are talking about 5,000 lines of code to trace not 5? If the storage is
initialise to NULL, even if c/malloc wern't called our tests for sucessful
allocation would pick up and flag a problem.

Second where are my taquitos!

Tom

Nov 14 '05 #15
I'd suggest that the lack of stdlib may have been the reason the original
problem, but the code as it stands is not good and will most liley cause
other problems. See my post further down for clarification.

"MK" <ms***@yahoo.co.uk> wrote in message
news:c0**********@aspen.sucs.soton.ac.uk...
No I didn't and that was the problem.
Thank you very much for your help Tom.
MK
Tom St Denis wrote:
"MK" <ms***@yahoo.co.uk> wrote in message
news:c0**********@aspen.sucs.soton.ac.uk...
I am a newbie. Please help. The following warning is issued by gcc-3.2.2
compiler (pc Linux):
================================================ ==================
read_raw_data.c:51: warning: assignment makes pointer from integer
without a cast
================================================ ==================

when the following piece of code was compiled. The offending statement
is calloc. A similar statement in the main() function passes without any
warning. Am I allowed to use calloc (and malloc) only within main() or
am I doing something very silly ??
=============================================
init(char *file, double *grid, \
double *start){
double *depth;
int pts
depth = calloc(pts,sizeof (double));

}

Did you include stdlib.h?

Tom

Nov 14 '05 #16
"EvilRix" <evilrix@[@@@]hotmail.com> writes:
"Tom St Denis" <to*@securescience.net> wrote in message
news:Nc******************@twister01.bloor.is.net.c able.rogers.com...

"Ricky Cormier" <evilrix@[@@@]hotmail.com> wrote in message
news:K7**************@newsfep3-gui.server.ntli.net...
> MK,
>
> 1. You are not initialising pts with a value
> 2. You should cast the (void *) returned from calloc to (double *)


No, no no no no. That hides bugs and is just not required.


[...] Just out of interest, what bugs will it hide? [...]


The bug the OP had in his code.

Martin
Nov 14 '05 #17

"Martin Dickopp" <ex****************@zero-based.org> wrote in message
news:c0*************@news.t-online.com...
"EvilRix" <evilrix@[@@@]hotmail.com> writes:
"Tom St Denis" <to*@securescience.net> wrote in message
news:Nc******************@twister01.bloor.is.net.c able.rogers.com...

"Ricky Cormier" <evilrix@[@@@]hotmail.com> wrote in message
news:K7**************@newsfep3-gui.server.ntli.net...
> MK,
>
> 1. You are not initialising pts with a value
> 2. You should cast the (void *) returned from calloc to (double *)

No, no no no no. That hides bugs and is just not required.
[...] Just out of interest, what bugs will it hide? [...]


Um, ok. Not sure I agree since the OP has posted elsewhere the lack of
stdlib (apprently) was his problem - would this really have hidden this?
The bug the OP had in his code.

Martin

Nov 14 '05 #18
"EvilRix" <evilrix@[@@@]hotmail.com> writes:
"Martin Dickopp" <ex****************@zero-based.org> wrote in message
news:c0*************@news.t-online.com...
"EvilRix" <evilrix@[@@@]hotmail.com> writes:
> "Tom St Denis" <to*@securescience.net> wrote in message
> news:Nc******************@twister01.bloor.is.net.c able.rogers.com...
>>
>> "Ricky Cormier" <evilrix@[@@@]hotmail.com> wrote in message
>> news:K7**************@newsfep3-gui.server.ntli.net...
>> > MK,
>> >
>> > 1. You are not initialising pts with a value
>> > 2. You should cast the (void *) returned from calloc to (double *)
>>
>> No, no no no no. That hides bugs and is just not required.
>
> [...] Just out of interest, what bugs will it hide? [...]


The bug the OP had in his code.


Um, ok. Not sure I agree since the OP has posted elsewhere the lack of
stdlib (apprently) was his problem - would this really have hidden this?


Yes. Try it. :)

Without a declaration, the compiler assumes that `calloc' returns `int'.
Usually it emits a warning if you try to assign an `int' to a pointer
type. But with the cast, you tell the compiler "shut up, I know what I'm
doing." Of course, in this case, you /don't/ know what you're doing,
i.e. in the absence of a `calloc' declaration, the code is wrong with or
without cast.

Martin
Nov 14 '05 #19

"Eric Sosman" <Er*********@sun.com> wrote in message
news:40**************@sun.com...
Ricky Cormier wrote:
[a top-post, here corrected]

"MK" <ms***@yahoo.co.uk> wrote in message
news:c0**********@aspen.sucs.soton.ac.uk...
I am a newbie. Please help. The following warning is issued by gcc-3.2.2 compiler (pc Linux):
================================================== ================
read_raw_data.c:51: warning: assignment makes pointer from integer
without a cast
================================================== ================

when the following piece of code was compiled. The offending statement
is calloc. A similar statement in the main() function passes without any warning. Am I allowed to use calloc (and malloc) only within main() or
am I doing something very silly ??
=============================================
init(char *file, double *grid, \
double *start){
double *depth;
int pts
depth = calloc(pts,sizeof (double));

}
[...]
1. You are not initialising pts with a value


Irrelevant, since `pts' is not being used. The lack
of a trailing semicolon, however, would be troublesome ...


It's used in the calloc call and unless it is initialise with a value it is
going to return an undefined number of doubles (or am I missing something
here?) since pts has no defined value prior to the call.
2. You should cast the (void *) returned from calloc to (double *)


No, NO, NO-NO-NO! Had he followed this bad advice, he
would probably not have received the error message. Silencing
the message without curing the error is a poor idea. It's the
appearance of the message that prompted MK to consult this forum;
if he had not been warned of a problem he'd most likely never
have learned how to correct it.


I don't agree (as I'm sure would many others), but fine. I'd suggest MK woul
d do well to read the plethora of posts on the subject of casting returns
from malloc and make his or her own mind up.
3. When declaring pointers it's a good idea to initialise them to NULL to start with (memory functions like free() will ignore NULL's)


The parenthetical remark is correct, but the rest of the
sentence is wrong-headed or even foolhardy. One important
disadvantage of the practice is that it prevents the compiler
from diagnosing the use of an uninitialized variable (if the
compiler has that ability). For example,

char *ptr;
switch (state) {
case 0:
ptr = "California";
break;
case 1:
ptr = "Siberia";
break;
}
printf ("You have been exiled to %s\n", ptr);

A helpful compiler will warn you that `ptr' may not have
been initialized by the time the printf() call is executed,
because no assignment will occur if `state' has a value
like, say, 42. A careful programmer will pay heed to the
warning and examine what possible values `state' may hold,
and might perhaps decide to use something other than a
`switch' to inspect the value.

However, if you wrote `char *ptr = NULL;' as recommended
by Mr. Cormier, the compiler would not detect the problem:
`ptr' has been initialized, albeit with a useless value.
Then if `state' is 42, you'll wind up executing

printf ("You have been exiled to %s\n", (char*)NULL);

Every software maintenance study I've ever read has found
that the cost of a bug rises with the amount of time it lives
in the code. Hence, earlier detection leads to lower cost,
so it's to your advantage *not* to suppress helpful warnings.


I said, 'good idea', however, I accept there are always exceptions to rules.
Regarding you eample, what happens is state is neither 0 nor 1 AND your
compiler isn't feeling very helpful? There is no guarentee the compiler
would pick up your potential bug as it would depend on the compiler and the
warning levels set.

Again, I suggest MK needs to review the many offerings in this group (and
this thread) and decide what suits his/her needs best.
--
Er*********@sun.com

Nov 14 '05 #20

"Martin Dickopp" <ex****************@zero-based.org> wrote in message
news:c0*************@news.t-online.com...
"EvilRix" <evilrix@[@@@]hotmail.com> writes:
"Martin Dickopp" <ex****************@zero-based.org> wrote in message
news:c0*************@news.t-online.com...
"EvilRix" <evilrix@[@@@]hotmail.com> writes:

> "Tom St Denis" <to*@securescience.net> wrote in message
> news:Nc******************@twister01.bloor.is.net.c able.rogers.com...
>>
>> "Ricky Cormier" <evilrix@[@@@]hotmail.com> wrote in message
>> news:K7**************@newsfep3-gui.server.ntli.net...
>> > MK,
>> >
>> > 1. You are not initialising pts with a value
>> > 2. You should cast the (void *) returned from calloc to (double *)
>>
>> No, no no no no. That hides bugs and is just not required.
>
> [...] Just out of interest, what bugs will it hide? [...]

The bug the OP had in his code.
Um, ok. Not sure I agree since the OP has posted elsewhere the lack of
stdlib (apprently) was his problem - would this really have hidden this?


Yes. Try it. :)


I did and yes you're right. Thanks.

Without a declaration, the compiler assumes that `calloc' returns `int'.
Usually it emits a warning if you try to assign an `int' to a pointer
type. But with the cast, you tell the compiler "shut up, I know what I'm
doing." Of course, in this case, you /don't/ know what you're doing,
i.e. in the absence of a `calloc' declaration, the code is wrong with or
without cast.

Martin

Nov 14 '05 #21
"EvilRix" <evilrix@[@@@]hotmail.com> wrote:

"Eric Sosman" <Er*********@sun.com> wrote in message
news:40**************@sun.com...
Ricky Cormier wrote:
[a top-post, here corrected]

"MK" <ms***@yahoo.co.uk> wrote in message
news:c0**********@aspen.sucs.soton.ac.uk...
> double *depth;
> int pts
> depth = calloc(pts,sizeof (double));

1. You are not initialising pts with a value
Irrelevant, since `pts' is not being used. The lack
of a trailing semicolon, however, would be troublesome ...


It's used in the calloc call and unless it is initialise with a value it is
going to return an undefined number of doubles (or am I missing something
here?) since pts has no defined value prior to the call.


Worse than that. Passing an invalid value to a pointer is legally
allowed to crash the program, because it invokes undefined behaviour.
2. You should cast the (void *) returned from calloc to (double *)


No, NO, NO-NO-NO! Had he followed this bad advice, he
would probably not have received the error message. Silencing
the message without curing the error is a poor idea. It's the
appearance of the message that prompted MK to consult this forum;
if he had not been warned of a problem he'd most likely never
have learned how to correct it.


I don't agree (as I'm sure would many others), but fine. I'd suggest MK woul
d do well to read the plethora of posts on the subject of casting returns
from malloc and make his or her own mind up.


Indeed. Post a single good reason for the cast.
3. When declaring pointers it's a good idea to initialise them to NULL
to start with (memory functions like free() will ignore NULL's)
A helpful compiler will warn you that `ptr' may not have
been initialized by the time the printf() call is executed,
because no assignment will occur if `state' has a value
like, say, 42. A careful programmer will pay heed to the
warning and examine what possible values `state' may hold,
and might perhaps decide to use something other than a
`switch' to inspect the value.

However, if you wrote `char *ptr = NULL;' as recommended
by Mr. Cormier, the compiler would not detect the problem:
`ptr' has been initialized, albeit with a useless value.

I said, 'good idea', however, I accept there are always exceptions to rules.
Regarding you eample, what happens is state is neither 0 nor 1 AND your
compiler isn't feeling very helpful? There is no guarentee the compiler
would pick up your potential bug as it would depend on the compiler and the
warning levels set.


Let's put it this way: with the null initialisation, your compiler is
not likely to warn no matter what, and the example still invokes
undefined behaviour; without the initialisation, the error is the very
same, but your compiler _could_ warn you. No guarantees here, except the
guarantee that the initialisation buggers your chances of the warning.

Richard
Nov 14 '05 #22

"EvilRix" <evilrix@[@@@]hotmail.com> wrote in message
news:VF**************@newsfep2-gui.server.ntli.net...
"Tom St Denis" <to*@securescience.net> wrote in message
news:Nc******************@twister01.bloor.is.net.c able.rogers.com...

"Ricky Cormier" <evilrix@[@@@]hotmail.com> wrote in message
news:K7**************@newsfep3-gui.server.ntli.net...
MK,

1. You are not initialising pts with a value
2. You should cast the (void *) returned from calloc to (double *)
No, no no no no. That hides bugs and is just not required.


It is good practice (read elsewhere in this group for the various

arguments made by others far more qualified than me) to do this. Notice I said
'should' and not 'must'! Just out of interest, what bugs will it hide? Good programming practice suggests it is always a good idea to be explicit when
coding rather than implicit (such as in this case an explicit cast rather
than an implicit one).
Well in this case it hides the fact that he didn't include stdlib. Also let
the warnings speak for you. Get a good compiler [re: gcc] and crank up the
warnings. Instead of randomly casting things (which can hide other bugs
like overflows and such) actually work to solve the problems found.
3. When declaring pointers it's a good idea to initialise them to NULL to start with (memory functions like free() will ignore NULL's)


This is retarded. First off, on error they will return NULL anyways.


I'm sorry you feel this is retarded. However, it is a good idea to
initialise ANY variable - including pointers! In the case of pointers it's


First off, not at the declaration and second, no it isn't. Again GCC will
warn you about using before declaring. So instead of writing messy code
like

int a=5,c = 3, d= 4;
char aa = 'b', *b = &aa;

etc....

Just declare your variables and initialize them prior to use in the C code.
common practice to use NULL. By initialising the pointer to NULL we have a
guarenteed value to test for. I accept your premise that c/malloc will
return NULL if the call fails (I never claimed otherwise) but what if the
programmer was daft enough to forget to call c/malloc (it could happen) and we are talking about 5,000 lines of code to trace not 5? If the storage is
initialise to NULL, even if c/malloc wern't called our tests for sucessful
allocation would pick up and flag a problem.


Then the compiler will warn about using an unitialized value. You do check
your compiler warnings right?

Tom
Nov 14 '05 #23
EvilRix wrote:

I'd suggest that the lack of stdlib may
have been the reason the original problem,
but the code as it stands is not good and will most liley cause
other problems. See my post further down for clarification.


If you don't top post to this newsgroup anymore,
then this will be the last time that you are annoyed by
a post like this.

http://www.cs.tut.fi/~jkorpela/usenet/brox.html
http://www.caliburn.nl/topposting.html

--
pete
Nov 14 '05 #24
EvilRix wrote:
[...]
> > 2. You should cast the (void *) returned from calloc to (double *)
>
> No, no no no no. That hides bugs and is just not required.

[...] Just out of interest, what bugs will it hide? [...]


The bug the OP had in his code.


Um, ok. Not sure I agree since the OP has posted elsewhere the lack of
stdlib (apprently) was his problem - would this really have hidden this?


The lack of stdlib _is_ the bug.

--

+---------+----------------------------------+-----------------------------+
| Kenneth | kenbrody at spamcop.net | "The opinions expressed |
| J. | http://www.hvcomputer.com | herein are not necessarily |
| Brody | http://www.fptech.com | those of fP Technologies." |
+---------+----------------------------------+-----------------------------+
Nov 14 '05 #25
(Top-posting corrected.)

MK wrote:

Tom St Denis wrote:
"MK" <ms***@yahoo.co.uk> wrote in message
news:c0**********@aspen.sucs.soton.ac.uk...
I am a newbie. Please help. The following warning is issued by gcc-3.2.2
compiler (pc Linux):
================================================ ==================
read_raw_data.c:51: warning: assignment makes pointer from integer
without a cast
================================================ ================== [...]depth = calloc(pts,sizeof (double));
[...] Did you include stdlib.h?

No I didn't and that was the problem.

[...]

A perfect example of the perennial "why is it a bad thing to cast the
return value from malloc/calloc" question.

Especially on a system where sizeof(int)!=sizeof(void*).

--

+---------+----------------------------------+-----------------------------+
| Kenneth | kenbrody at spamcop.net | "The opinions expressed |
| J. | http://www.hvcomputer.com | herein are not necessarily |
| Brody | http://www.fptech.com | those of fP Technologies." |
+---------+----------------------------------+-----------------------------+
Nov 14 '05 #26

In article <VF**************@newsfep2-gui.server.ntli.net>, "EvilRix" <evilrix@[@@@]hotmail.com> writes:
[re casting malloc/calloc]

It is good practice (read elsewhere in this group for the various arguments
made by others far more qualified than me) to do this.
Perhaps you should read those threads again. There were, as I recall,
a grand total of two qualified advocates of casting malloc/calloc in
the most recent tussle over this issue. One, P. J. Plauger, suggested
that the cast was appropriate in certain situations; this is not one
of them. The other, Sidney Cadot, makes an interesting case, but even
he admits the danger of omitting stdlib.h; he just feels that modern
implementations should flag that anyway, eliminating the need to catch
it by not casting malloc/calloc. He's recommending a different trade-
off, in other words.

How you derive "good practice" from that is beyond me. If you believe,
for some unimaginable reason, that casting malloc/calloc is "good
practice", fine; but vague references to recent threads in c.l.c to
support your claim is bogus.
Notice I said
'should' and not 'must'! Just out of interest, what bugs will it hide?
Other posters have already noted the first one: it hides the failure
to include stdlib.h and have a prototype for calloc in scope.

It also hides the fact that the code invokes undefined behavior,
because it creates a pointer from an int. And yes, there are
conforming hosted C implementations in use where you cannot convert
a pointer to an int and back again successfully. One is being
discussed in another thread right now.
Good
programming practice suggests it is always a good idea to be explicit when
coding rather than implicit (such as in this case an explicit cast rather
than an implicit one).


I believe good programming practice suggests it is always better to
be right than to be wrong. This code was wrong, and your "fix" to it
was wrong.

Advocate casting calloc/malloc if you like. Don't have much hope of
converting the c.l.c majority to your position, though, and please
don't claim that we're already there.

--
Michael Wojcik mi************@microfocus.com

A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
-- David Bonde
Nov 14 '05 #27
EvilRix wrote:
1. You are not initialising pts with a value
2. You should cast the (void *) returned from calloc to (double *)
No, no no no no. That hides bugs and is just not required.

It is good practice (read elsewhere in this group for the various arguments
made by others far more qualified than me) to do this.
I have trouble understanding how you could come to this conclusion,
given that the "generally-anti-cast" crowd probably outnumbers the
"generally-pro-cast" crowd by something like 15-to-1 in this newsgroup.
I've seen people claiming it's an open-and-shut case against casts; and
I've seen people making the case that it's not a black-and-white thing,
and a case can be made for casting (that includes me and Mr. Plauger);
however, I have seen no-one claim it is unqualified, beyond-discussion
good practice to do malloc casting, as you suggest.
[...] Good
programming practice suggests it is always a good idea to be explicit when
coding rather than implicit (such as in this case an explicit cast rather
than an implicit one).


"explicit cast" is a tautology, and "implicit cast" does not exist. The
word you're probably looking for is "conversion". I have had to un-train
myself for the same mistake :-)

Best regards,

Sidney

Nov 14 '05 #28

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

Similar topics

5
by: Koster | last post by:
Sorry for the re-post, but my previous question was left unanswered. I have a question about the appropriateness of calloc. Consider an array of pointers to structs which need to be allocated...
14
by: Rahul Gandhi | last post by:
Which one is more fast? malloc followed by memset or calloc
16
by: David Ford | last post by:
I have a macro that I use across the board for freeing ram. I'd like to clean up my code so I don't get these warnings. #define sfree(x) _internal_sfree((void **)&x) #define _internal_sfree(x)...
6
by: brian | last post by:
I went through my implementation's (BSD) source code for calloc(), and if no more than one object is being allocated, the code will still execute the following if() (from...
11
by: lohith.matad | last post by:
Hi all, Though the purpose of both malloc() and calloc() is the same, and as we also know that calloc() initializes the alloacted locations to 'zero', and also that malloc() is used for bytes...
8
by: venkatesh | last post by:
hai to everybody, i am having doubt in difference between the malloc and calloc function. please tell where to use and when to use those functions?
17
by: Mike | last post by:
Hello, I have following existing code. And there is memory leak. Anyone know how to get ride of it? function foo has been used in thousands places, the signature is not allowed to change. ...
6
by: Francois Grieu | last post by:
Hello, I'm asking myself all kind of questions on allocating an array of struct with proper alignment. Is the following code oorrect ? I'm most interested by the statement t =...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.