From: horst DOT kraemer AT t-online DOT de (Horst Kraemer) Newsgroups: comp.os.msdos.djgpp Subject: Re: new vs malloc Date: Sun, 20 Feb 2000 00:43:08 GMT Organization: T-Online Lines: 57 Message-ID: <38aebc31.19427507@news.btx.dtag.de> References: <38AD8622 DOT AE067F97 AT tiscalinet DOT it> <004101bf7a97$06ff2ca0$cff0fea9 AT stevenhe> <88lt6e$9pj$1 AT nets3 DOT rz DOT RWTH-Aachen DOT DE> <01bf7ba9$8fb5a980$c3247d81 AT default> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 8bit X-Trace: news07.btx.dtag.de 951007354 19017 0306239354-0001 000220 00:42:34 X-Complaints-To: abuse AT t-online DOT de X-Sender: 0306239354-0001 AT t-dialin DOT net X-Newsreader: Forte Free Agent 1.11/32.235 To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Reply-To: djgpp AT delorie DOT com On 19 Feb 2000 13:44:37 GMT, "doug" wrote: > > In a nutshell: if you write C++, use new. If you write C, use > > malloc(), and *don't* cast the return value, as it will actually hide > > potential problems, instead of fixing any. > > Can you give me an example. I like my C programs to compile > with as few warnings as possible, even if they are compiled as C++ Sorry. If you compile a program "as C++" it is a C++ program and not a C program. And there is no point compiling a valid C program "as C++" although since Charles Petzold (in his excellent book "Programming windows") recommended compiling C programs "as C++" people ruminate that this is GOOD... Imho the only profit you gain is that you have to do the malloc-cast which is only a syntactical "ceremony" without any practical usefulness. But if you prefer C++ then stick to C++ by all means - but don't call your programs C programs ;-) C and C++ are distinct languages with a lot of similarities. And this "lot" is the dangerous part because it makes you forget that there _are_ differences. > and I cast the returned value from malloc to achieve this. Can you > give me an example of where this casting may cause problems in > a C program? int main() { char* p = malloc(50); } Now you will get a diagnostic from a C compiler. As there is no declaration for malloc in scope (because you forgot to #include stdlib.h) the compiler will assume that malloc returns an int and there is no implicit conversion from int to char*. If you cast char* p = (char*)malloc(50); there is no diagnostic. The compiler still assumes that malloc returns an int and assumes that the value returned by malloc is an int to be casted to a char*. This is desastrous if int and char* have different sizes and/or representations. In C++ you have no option because you always have to cast explicitly. The stdlib problem doesn't exist in C++ because in C++ it is an error to call malloc without #including stdlib, while it is permitted in C. Regards Horst