The strange behavior of this code

  • Thread starter Thread starter dh
  • Start date Start date
D

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
 
dh said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top