Solved

MemoryMappedFile Issue C#/C++

Posted on 2007-04-05
6
957 Views
Last Modified: 2013-11-07
I have a Memory Mapped File that is being populated by a seperate C++ application and I am reading the contents of that file using a C# Windows Application.  Everything works fine from the perspective of opening the file and view, retrieving the data and working with the resultant byte array.
However, I need to zero-out the memory when I am done and I cannot get that to work.  When I call the ZeroMemory Kernel Method, I keep getting the following:

System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Here the DLL Import signature:

[DllImport("kernel32", SetLastError = true)]
public static extern void ZeroMemory(IntPtr dest, int size);

Can somebody please help?
0
Comment
Question by:ktola
  • 3
  • 2
6 Comments
 
LVL 45

Expert Comment

by:Kdo
ID: 18861712
Hi ktola,

Just to be sure, the first parameter to ZeroMemory is a pointer to void.  (Or have you overloaded the function?)

Also, you need to call ZeroMemory before closing the file or unmapping the region.


Kent
0
 

Author Comment

by:ktola
ID: 18861737
I implemented IDisposable in my MemoryMappedFile class - here is the overloaded Dispose method that is called:

protected virtual void Dispose(bool disposing, int MemorySize)
{
     if (IsOpen)
     {
          if (MemorySize > 0)
               Win32MapApis.ZeroMemory(_hMap, MemorySize);
          Win32MapApis.UnmapViewOfFile(_hMap);
          Win32MapApis.CloseHandle(_hMap);
     }
     _hMap = NULL_HANDLE;

     if (disposing)
          GC.SuppressFinalize(this);
}

_hMap is the pointer to the file mapping created with this call:

map._hMap = Win32MapApis.CreateFileMapping(hFile, IntPtr.Zero, (int)protection, (int)((maxSize >> 32) & 0xFFFFFFFF), (int)(maxSize & 0xFFFFFFFF), name);

I have not overloaded anything at this point.  Finally, here is the main method call:

                    map = MemoryMappedFile.Open(MapAccess.FileMapAllAccess, mappedFileName);
                    if (map._hMap != MemoryMappedFile.NULL_HANDLE)
                    {
                        using (Stream dataMem = map.MapView(MapAccess.FileMapAllAccess, 0, maxBytes))
                        {
                            if (dataMem.Length > 0)
                            {
                                dataBytes = new byte[dataMem.Length];
                                dataMem.Read(dataBytes, 0, dataBytes.Length);
                                dataValues = Encoding.Unicode.GetString(dataBytes).Trim();
                                if (dataValues.Length > 0)
                                {
                                    memSize = sizeof(char) * dataValues.Length;
                                    //Do Work
                                }
                                else
                                    memSize = 0;
                                dataMem.Close();
                            }
                        }
                        map.Dispose(true, memSize);
0
 
LVL 48

Accepted Solution

by:
AlexFM earned 500 total points
ID: 18862475
hMap is not pointer, this is handle to memory mapped file. Pointer is returned by MapViewOfFile API. I think that this is map.MapView in your code. Any direct access to memory should be done with value returned by MapViewOfFile and not with value returned by CreateFileMapping.
Anyway, there is no need to zero memory before closing, you can remove this line.
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:ktola
ID: 18883021
Unfortunately, I need to zero the memory as the C++ application on the other side is looking for the memory to be zeroed out so it knows I have cleared the data.  It then fills the file with new data.
0
 
LVL 45

Expert Comment

by:Kdo
ID: 18883237
That's fine.

As Alex pointed out, you need to zero the memory starting at a memory address, not the value of the file handle.


Kent
0
 

Author Comment

by:ktola
ID: 19049875
Thank you for all of your help.  I ended up scrapping the entire concept and, instead, building a port-level queue to handle the traffic in C++.  That queue exposed an interface for .NET and that seemed to suffice.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now