Re: doubt on char *
  Home FAQ Contact Sign in
comp.lang.c only
 
Advanced search
POPULAR GROUPS

more...

 Up
Re: doubt on char *         

Group: comp.lang.c · Group Profile
Author: pete
Date: Jun 11, 2008 20:02

CD1 wrote:
> On Jun 10, 9:15 am, Chris Dollin hp.com> wrote:
>> rams wrote:
>>> yes ,allocate memory for destbuf using malloc() &strlen()
>>> like destbuf=(char *)malloc(1+ strlen(sourcebuf)*sizeof(char) );
>> (a) there's no need to, and good reasons for not, cast the `malloc`
>> result to `char*`.
>>
>> (b) `sizeof char` is 1 by definition.
>>
>> char *destbuf = malloc( 1 + strlen( sourcebuf ) );
>>
>> is, I think, clearer and safer. (I'd write `+ 1` rather than `1 +`,
>> but I can see the point of marking the one-more-than in this way.)
>>
>> --
>> "Shopping." /Barrayar/
>>
>> Hewlett-Packard Limited registered no:
>> registered office: Cain Road, Bracknell, Berks RG12 1HN 690597 England
>
> Well, I think the statement:
>
> char *destbuf = (char *) malloc(1 + strlen(sourcebuf) * sizeof(char));
>
> is clearer and safer than yours, for the following reasons:
>
> (a) If destbuf is of type char *, it makes the code clearer to cast
> the return of malloc to that type, even if it's unnecessary. And if
> I'm not mistaken, in C++ you must cast void * to char * explicitly, so
> in case this code has to be compiled in a C++ environment, no changes
> would be necessary.
> (b) If you use sizeof to calculate the size of the other primitive
> types, pointers and structs, why not use it also to calculate the size
> of a char? I didn't know sizeof(char) is 1 by definition, but it's an
> "exception" in your coding rules: "use sizeof to calculate the size of
> every type, but char".
>
> Just my opinion :)

I use two distinct formats and one related format,
for most malloc calls:

#include

a = malloc(string_length + 1);
b = malloc(N * sizeof *b);
c = malloc(sizeof *c);

--
pete
no comments
diggit! del.icio.us! reddit!