Re: newbie on pointers
Henrietta Denoue wrote:
Hi,
What happens to a global pointer that is to be used in various
other objects, is instantiated in one object, then this second
object is deleted ? Is the pointer still valid ? like pseudo-code
---------------------------
// my global pointer, not a member of Classes A or B
X *x;
class A{
....
x = new X();
... do something with x
}
Class B {
...
do something with x;
}
int main()
{
A a;
B b;
a = new A();
....
delete a;
---------------
My question is : Is x still valid in B evenif A is deleted ?
"Henrietta Denoue" <henrietta@netcalcul.fr> wrote in message
news:eup2cv$2u9t$1@news01.tp.hist.no...
Thanks guys for the answer,
and sorry for the typo, I mean 'a' and 'b' as pointers, just
forgot the '*'.
For some reason function argument does not work. 'A' and 'B' have
of course destructors but do not touch 'x' in their destructors.
What 'A' does with x (x is an object with its own pointers
to other objects and arrays) is to process some data and fill in some
arrays inside 'x'. 'x' is actually a pointer to a an object of a class
that reads a file of certain format. The filename is transferred to
it through a gui. If the user change the file, of course 'x' is deleted
inside 'A' and a new 'x' is instantiated. But when I am finished with
'a' (deleted), the contents of 'x' is not what is
supposed to be. Therefore I gave up the idea of
using function arguments (I sent the address of
'x' to 'a' as an argument to a fuction).
So I switched to a shared /global variable. It seems to work but I
am not comfortable wit the idea. I would have preferred to do it
as I did first but it just didn't work.
If it did not work passing it as a parameter, then something is wrong.
Using it as a global could just be hiding (even temporarily) the problem.
It sounds to me like class A may be newing something things, storing them to
class X, then when class A is destroyed it deletes what it created, making
X's pointers invalid. Or, somewhere you are overflowing memory.
Either way, it has to be fixed. Take a good look at both A and B and what
they are doing to pointers, make sure that anything newed in A or B and
assigned to X isn't being deleted accidently or something. Without seeing
code it's hard to say.
If you can't find the error, try posting the code here, if small, or to some
pasting bin and giving a link and maybe we can figure it out. It should be
fixed, however. Rearranging things in memory (such as chaning from a parm
to a global) making them work almost always means you have memory problems
somewhere and actually didn't fix the problem, just hid it.