delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/12/22/22:18:33

From: Weiqi Gao <weiqigao AT a DOT crl DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: djgpp strangeness
Date: Wed, 22 Dec 1999 20:04:17 -0600
Organization: CRL Network Services
Lines: 48
Message-ID: <38618321.667C7F69@a.crl.com>
References: <tmU74.34$Fc6 DOT 1542 AT weber DOT videotron DOT net> <14684.897$Qz2 DOT 16629 AT wagner DOT videotron DOT net> <Yue84.371$36 DOT 7194 AT carnaval DOT risq DOT qc DOT ca>
NNTP-Posting-Host: a116024.stl1.as.crl.com
Mime-Version: 1.0
X-Mailer: Mozilla 4.51 [en] (X11; I; Linux 2.2.5-15 i586)
X-Accept-Language: en
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Alain Magloire wrote:
> 
> If you are writting in C++, then do.  If you want to use C, then use C.
> malloc/free are not the preferred way to allocate objects and manage memory,
> in C++.
> 
> I do not remember what the std say, but malloc() will give
> uninitialized memory, and free () is not even require to invoke the
> destructor, when the object is collected.
> 
> Use new and delete.

I was thinking along the same lines when I tested my theory out with the
following program:

==========8<==========8<==========8<==========
#include <iostream>
#include <cstdlib>

class X {
  int i;
public:
  X(int i_) : i(i_) {}
  void foo() { cout << "i = " << i << endl; }
  void setI(int i_) { i = i_; }
};

int main() {
  X *xp = (X *) malloc(sizeof(X));
  xp->setI(100);
  xp->foo();
}
==========8<==========8<==========8<==========

And it worked!  It's bad style, I know, but does not generate any
errors, and prints out '100' as expected.

Valkir's classes might be more complicated than the one above, which
could cause an error when used with malloc().

> Valkir (jfd50 AT videotron DOT ca) wrote:
> : Here's the code:
> : int main()
> : [...]

-- 
Weiqi Gao
weiqigao AT a DOT crl DOT com

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019