[lug] new operator in C++

Stephen Queen svq at peakpeak.com
Sat Apr 27 19:06:19 MDT 2002


Tkil wrote:

> >>>>> "DS" == D Stimits <stimits at idcomm.com> writes:
>
> i think you misunderstood my surprise.
>
> DS> delete was called after each new; thus the same memory slot was
> DS> likely to be reused each time.
>
> right.  but it wasn't, and that's what surprised me.  if it *had* been
> re-used, i would have expected to see 1 2 3 4 5 ... and so on.  but
> having just 1, then that constant number -- very strange!
>
> DS> Had you done all the new operators in a row on separate variables,
> DS> your results would not have been the same in all likelihood. Or if
> DS> you had done other memory operations possibly the slot being used
> DS> would have been different.
>
> weird, i am getting the same address each time.  something is
> overwriting it with a consistent value each time through the loop.
> actually, even in the first block (that's not a loop).
>
> i wonder what's doing it?
>
> and it does seem to do something more than just "put it on a free
> list", which is what i thought; if i try to do "*pi = 0" after the
> delete, i get a SEGV (even though pi itself has the same value as
> before the delete.)
>
> oh well.  confused, and too hungry to step through libstdc++ and glibc
> to figure out what's going on.
>
> t.

I ran almost the same program on my machine and did get 1 2 3 4 5...,
here is the complete listing

#include <iostream>
void main( )

#include <iostream.h>
void check(void);
void main( )
{
     for (int i = 0; i < 100 ; ++i) {
        int * pi = new int;
        ++(*pi);
        cout << *pi << endl;
        delete pi;
    }
     return 0;
}

So then I tried
#include <iostream>
void check(void);
void main( )
{
     for (int i = 0; i < 100 ; ++i) {
        check();
     }
     return 0;
}
void check()
{
        int * pi = new int;
        ++(*pi);
        cout << *pi << endl;
        delete pi;
}

and got the same results (1 2 3 4...).
It did prove that new does not initialize the new memory to zero. That is
what I wanted to know.

Thanks to all of you for the assistance.
Steve Queen





More information about the LUG mailing list