Sign in to follow this  
Aileen

memory collapse?

Recommended Posts

I added a new pointer 'Buffer' of type newbuf to a class as its private variable. (newbuf is a struct I defined) I initalized this pointer as follows: newbuf temp; temp.fontIndex = 1; temp.newbufSize = 2; temp.ss = new WCHAR; StringCchCopy(temp.ss,temp.newbufSize,m_pwszBuffer); Buffer = &temp; Then when I "run to cursor", I found that in one function under another class, there are three integers defined as follows: int x,nX,X2; And after running the above step, I see the value of x, nX, X2 equal to the values of temp.fontIndex, temp.newbufSize, and temp.ss respectively. The x,nX,X2, without initialized, should be all '0', rite? But, they are not. Then the wired thing happened. once I changed the value of x, nX, X2, the value of temp.fontIndex, temp.newbufSize, and temp.ss change accordingly as well. It seems like two variables happened to locate in the same memory, is it? Becuase the Buffer I added is in a different class from where the three variables, x,nX,X2 were defined. And the three variables' defination shouldn't have an access to the priave variable Buffer in another class. am I right? How can I change x, nX, X2 without changing my buffer?? can someone help me? thanks a lot

Share this post


Link to post
Share on other sites
It looks like your:

newbuf temp;

is a local variable to me. What will happen is that after you assign the address to the Buffer pointer and the function exits, the temp variable, and thus what Buffer points to, will be destroyed. This (stack) memory will then be used by later operations, explaining the behaviour you report.

It would appear that what you want would be more like:

Buffer=new newbuf();
Buffer->fontindex=1; // etc

with a corresponding

delete Buffer;

in the enclosing objects destructor, or wherever most appropriate.

BTW, this line:

temp.ss = new WCHAR;

looks highly suspect. That will allocate just one WCHAR, not a block of them. It would appear from the next line that you are trying to copy a string into this memory, which will cause horrible problems.

Really you'd be better to use std::wstring, but if you must allocate like that, the correct form would be:

temp.ss = new WCHAR[NumberOfCharactersNeeded+1];

to leave space for the string you are copying in plus the null terminator.


HTH Paul

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this