TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: BRIAN WOOD
from: PETER HAYWOOD
date: 1998-02-24 01:02:00
subject: Re: more questions about new

Groovy hepcat Brian Wood jived with All on 02 Feb 98  05:19:06!
more questions about new's a cool scene. Dig it!
 BW> void Enlarge(char *p)
 BW> {
 BW> char *x=new char[20];
 BW> delete[] p;
 BW> p=x;
 BW> }
 BW> void main()
 BW> {
 BW> char *sz=new char[10];
 BW> Enlarge(sz);
 BW> }
  Arguments to functions are treated as automatic variables. Changing
the value of an argument does not change the original variable that
was passed from the calling function.
 BW> Using the debugger, it looks like p does get the address of x, but
 BW> after the function, sz is the same address, an empty string?  Trying to
 BW> do it different, like this...
  You can't be sure it's an empty string or whether it's something
else. After memory has been freed (deleted), a pointer to that freed
memory can cause undefined behaviour when dereferenced.
  sz, in the code above, has not changed. Changing p in the Enlarge()
function does not change sz in main(). They are diferent and separate
variables - in diferent functions!
 BW> char *Enlarge(char *p)
 BW> {
 BW> char *x=new char[20];
 BW> delete[] p;
 BW> return x;
 BW> }
 BW> void main()
 BW> {
 BW> char *sz=new char[10];
 BW> sz=Enlarge(sz);
 BW> }
 BW> so far seems to work, but am I even on the right track?
  Yes. This way works. This is correct.
  However, I don't know why you don't just use realloc() or something
to enlarge a block of memory. I don't know if there's some operator in
C++ analogous to realloc(), but if there isn't you could just use
realloc() itself.
                                                  Wolvaen
... Don't say "Eat my shorts!" unless you have edible shorts.
--- Blue Wave/RA v2.20
---------------
* Origin: The Gate, Melbourne Australia, +61-3-9809-5097 33.6k (3:633/159)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.