.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

PInvoke: When is the memory allocated by the CLR marshaller freed?

Posted By:      Posted Date: October 14, 2010    Points: 0   Category :.NET Framework

I am using PInvoke to pass the following class to unmanaged C++ when the app starts up. All the values are passed in correctly as I step through the code. Inside the called C++ method I save a the ptr to the passed in struct.

    public class Config
        public int Speed;

        [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.LPStr, SizeConst = 2)]   
        public string[] Settings = new string[2];


Matching C++ struct

struct config 
    int            Speed;
    char*        Settings[2];



This is the method in C++ that saves ptr to the class that is passed in

Config *m_config;

void SetConfig(Config *config)


    m_config = config;


Question: if the marshaller allocated memory for the C++ struct at the time of marshaling when does it free the memory?

If I save the ptr to the passed in struct, will t

View Complete Post

More Related Resource Links

How to check how much memory from .NET process is allocated in pagefile?

Hi How to check how much memory from .NET process is allocated in pagefile? I was trying use task manager and perfmon but I could not find any counter/column that would tell me how much memory from specific .NET process is in pagefile. Regards

How to find out how memory is allocated in SQL Server 2005/2008?


I want to find out how to get memory information from SQL Server using DMVs that will equal to or be very close to the memory shown in Mem Usage column of Windows Task Manager for sqlservr.exe.   I have tried to sum single_pages_kb, multi_pages_kb, and virtual_memory_committed_kb from sys.dm_os_memory_clerks but the combined total is still less than the Mem Usage from Windows Task Manager.  

How to detect and avoid memory and resources leaks in .NET application

Despite what a lot of people believe, it's easy to introduce memory and resources leaks in .NET applications. The Garbage Collector, or GC for close friends, is not a magician who would completely relieve you from taking care of your memory and resources consumption.

I'll explain in this article why memory leaks exist in .NET and how to avoid them. Don't worry, I won't focus here on the inner workings of the garbage collector and other advanced characteristics of memory and resources management in .NET.

file upload in chunks or not buffering in memory before writing to disk?


What are the options for handling file uploads to reduce the memory footprint?  Is there a way to upload in chunks?  Is there a way to stream upload directly to disk instead of loading entire file in server memory?


Visual Studio 2008 Memory problems


My memory in task manager reaches about 900,000K  and I don't know why it does this. Definately slows everything down, especially when I rebuild my tableAdapters, takes about 30 seconds sometimes to rebuild the project.

Crystal Report gives System.AccessViolationException: Attempted to read or write protected memory. T


when a crystal report for same id is opened again at same time or refreshed then it gives the

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

Stack Trace is :-

Stack Trace:

[AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.]
CrystalDecisions.ReportAppServer.Controllers.DatabaseControllerClass.SetConnectionInfos(ConnectionInfos ConnectionInfos) +0
CrystalDecisions.CrystalReports.Engine.Table.ApplyLogOnInfo(TableLogOnInfo logonInfo) +362
CrystalDecisions.CrystalReports.Engine.ReportDocument.SetTableLogon(Tables tables, String user, String password, String server, String database, Boolean ignoreCase) +258
CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDatabaseLogon(String user, String password, String server, String database, Boolean ignoreCase) +204

Maximum memory for string ? . System.MemoryOutOfException Occurs when reading the Content of the fil



I have a C++ code which reads a file [vtk file - its similar to text file only]. and try to store it in string.

here's the code:

String^ ParallelProjectionRenderer::GetVolumeDataAsString(String^ FileName)

    vtkSmartPointer<vtkDataSetWriter> sWriter = vtkSmartPointer<vtkDataSetWriter>::New();

    String^ FileName = "D:\\Users\\...";

    char * sptName = static_cast<char *>(Marshal::StringToHGlobalAnsi(FileName).ToPointer());







    String^ result= File::ReadAllText(FileName);   [it breaks here with system.memoryoutofexception when the file size is huge]

    return result;


this code executes fine when the file size is less than 8mb.

I wanted to know whats the maximum memory allocated to the string.

As a workaround i skipped reading out in C++ code. and i tried to read the file contents in asp.net C# code and stor

Tools for memory error check in VS2005


Dear all,

I am going to write vs2005 program with ASP.NET and C++.

As you know that C++ will involve a lot of memory error handling.

Do you know is there any tools for checking memory error in Code Behind C++??

CLR Inside Out: Memory Usage Auditing For .NET Applications


Memory usage can have a direct impact on how fast an application executes and thus is important to optimize. In this article we discuss the basics of memory optimization for .NET programs.

Subramanian Ramaswamy and Vance Morrison

MSDN Magazine June 2009

Debug Leaky Apps: Identify And Prevent Memory Leaks In Managed Code


When is the .NET Garbage Collector unable to reclaim memory? The answer might surprise you. Stay tuned.

James Kovacs

MSDN Magazine January 2007

CLR Inside Out: Investigating Memory Issues


Memory issues can manifest in a wide variety of ways. This column shows you how to collect the data you need to determine what types of mem¬ory issues you are experiencing.

Claudio Caldato and Maoni Stephens

MSDN Magazine November 2006

{ End Bracket }: Transactions for Memory


Injecting parallelism into your app is easy-managed code offers things like explicit threading and a thread pool for that. Ensuring your code remains correct when run in parallel, on the other hand, is not quite so simple.

Joe Duffy

MSDN Magazine January 2006

Memory Models: Understand the Impact of Low-Lock Techniques in Multithreaded Apps


Because the use of low-lock techniques in your application significantly increases the likelihood of introducing hard-to-find bugs, it is best to use them only when absolutely necessary. Here Vance Morrison demonstrates the limitations and subtleties low-lock techniques so that if you are forced to use them you have a better chance of using them correctly.

Vance Morrison

MSDN Magazine October 2005

Memory Lane: Rediscover the Lost Art of Memory Optimization in Your Managed Code


Managed applications rely on the garbage collector in the .NET Framework to allocate and clean up memory. The little CPU time spent performing garbage collection (GC) is usually a fair trade-off for not having to worry about memory management. But for applications in which CPU time and memory are precious resources, minimizing the time spent garbage collecting can greatly improve application performance and robustness. Find out how to manage memory all over again.

Erik Brown

MSDN Magazine January 2005

Visual C++ 6.0: Don't Let Memory Allocation Failures Crash Your Legacy STL Application


Most C++ developers make extensive use of the Standard Template Library (STL) in their code. If you are one of them and are using STL and Visual C++ 6.0 directly out of the box, your application is at high risk of crashing under low memory conditions. The problem arises because checking for failure of operator new is such an uncommon practice. To make things worse, when new does fail, the response is not standard. Some language compilers return NULL while others throw an exception.In addition, if you are using STL in an MFC project, be aware that MFC has its own set of rules. This article discusses these problems, explains how the default behavior has changed in Visual C++ .NET 2003, and outlines the changes you must make if you're using Visual C++ 6.0 so that you can safely use the STL when operator new fails.

James Hebben

MSDN Magazine September 2003

Design: Inspect and Optimize Your Program's Memory Usage with the .NET Profiler API


Developers using .NET often make memory leak tracking a low priority because the common language runtime takes care of garbage collection. What few developers realize, however, is that their objects' lifespans, along with their size and what other objects have been instantiated, all affect how they are cleaned up. Depending on the particular circumstances, these combinations can negatively affect performance, especially over the lifetime of an application. This article presents a way for developers to see memory usage and understand garbage collection using the .NET Profiler API. Along the way, a sample application to demonstrate these principles is built.

Jay Hilyard

MSDN Magazine January 2003

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend