Subj : Re: Memory Pointers and Free To : borland.public.cpp.borlandcpp From : Alistair Date : Sun Jul 25 2004 02:47 pm Interesting, a simple mistake of forgetting to write the casting from void * to s_a * on the memory allocation in this quickly written example and I have caused a raft of discussion on whether it would compile. Including the cast, it does compile and works perfectly fine in C++, with the compiler I have (vc++6, vc++7 (.net) and borland c++ builder 4,5 + 6). I thought it would cause a memory leak, but I wasnt too sure, thanks for the help! Oh, and I have never really done C, this is an interesting difference and explains some of the code I have seen some people write in C++. Many Thanks Alistair "Wayne A. King" wrote in message news:41036c9b.6109911@newsgroups.borland.com... > On Sun, 25 Jul 2004 01:27:49 +0100, =?ISO-8859-15?Q?Jo=E3o?= Paredes > wrote: > > >> s_a *a = malloc(sizeof(s_a)); > >> a->somedata = malloc(512); > > >with the declaration for the structure and variable you posted, I don't > >believe that would even compile. > > Interesting example of the differences between C and C++. > You're right, it wouldn't compile. But for different reasons in the two > languages. > > >If you create a type with "struct something > >{...};" you would have to declare variables with "struct something myvar;". > > True for C (C90), but not for C++. In the former, this is an error: > s_a *a = malloc(sizeof(s_a)); > It must be this for C90: > struct s_a *a = malloc(sizeof(struct s_a)); > > However, in C++ the original post is OK as the "struct" keyword > may be omitted. However, in C++ the original example will fail > for another reason - which doesn't apply to C90 - the void* > returned by malloc must be typecast in C++ but may be > omitted in C90. So C++ would look like this: > s_a *a = (s_a*)malloc(sizeof(s_a)); > > Note that C++ will also accept the explicit "struct" keyword, > and C will accept the typecast. So a form which would pass > both C and C++ would be like this: > struct s_a *a = (struct s_a*)malloc(sizeof(struct s_a)); > > > -- > Wayne A. King > (waking@idirect.com, Wayne_A_King@compuserve.com) .