471,348 Members | 1,741 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,348 software developers and data experts.

The strange behavior of this code

dh
If the put the code,

IntPtr ptr = Marshal.AllocCoTaskMem(4);
hr = em.Next(monikers.Length, monikers, ptr);
x = Marshal.ReadInt32(p);
// Use x below
....
....
Marshal.FreeCoTaskMem(p);

into a loop like this,

while(i < 5)
{
IntPtr ptr = Marshal.AllocCoTaskMem(4);
hr = em.Next(monikers.Length, monikers, ptr);
x = Marshal.ReadInt32(p);
// Use x below
...
...
Marshal.FreeCoTaskMem(p);
}

It would throw AccessViolation exception. Sometimes at AllocCoTaskMem();
other times at FreeCoTaskMem(). Any idea why that?

Thanks!
DH
Jul 31 '08 #1
1 1279
dh wrote:
If the put the code,

IntPtr ptr = Marshal.AllocCoTaskMem(4);
hr = em.Next(monikers.Length, monikers, ptr);
x = Marshal.ReadInt32(p);
// Use x below
...
...
Marshal.FreeCoTaskMem(p);

into a loop like this,

while(i < 5)
{
IntPtr ptr = Marshal.AllocCoTaskMem(4);
I don't see that you free that memory anywhere in the code...
hr = em.Next(monikers.Length, monikers, ptr);
x = Marshal.ReadInt32(p);
Where does the p variable come from?
// Use x below
...
...
Marshal.FreeCoTaskMem(p);
If you free the memory that p points to, and then try to access it in
the next iteration of the loop, that memory area may have been allocated
to another process. That would definitely cause an access violation.
}

It would throw AccessViolation exception. Sometimes at AllocCoTaskMem();
other times at FreeCoTaskMem(). Any idea why that?

Thanks!
DH


--
Göran Andersson
_____
http://www.guffa.com
Jul 31 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

19 posts views Thread by david | last post: by
20 posts views Thread by Pilcrow | last post: by
reply views Thread by Ronak mishra | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.