Question: I'm trying to implement OpenCV into my application but every time I call a function there is a memory leak. I guess it has something to do with how I have used the library with Visual Studio but I tested it with a blank project and it seemed to work fine with the same settings.

The code I'm trying to implement into:

```
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    int nRetCode = 0;

    // initialize Microsoft Foundation Classes, and print an error if failure
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
    {
        _tprintf(_T("Fatal Error: MFC initialization failed\n"));
        nRetCode = 1;
    }
    else
    {
        // Application starts here...

        // Time the application's execution time.
        TIMER start;

                // CODE TO GO HERE!

        TIMER end;

        TIMER elapsed;

        elapsed = end - start;

         __int64 ticks_per_second = start.get_frequency();

        // Display the resulting time...

        double elapsed_seconds = (double)elapsed.get_time() / (double)ticks_per_second;

        cout << "Elapsed time (seconds): " << elapsed_seconds;
        cout << endl;
        cout << "Press a key to continue" << endl;

        char c;
        cin >> c;
     }

    return nRetCode;
}

```

If I implement something as simple as:

```
cv::Mat aVar;

```

in the space where I have put "CODE TO GO HERE!" Visual Studio says there is a memory leak once the program has terminated. Any ideas what the problem could be?

Answer: 
Like I said in your last post, the details are important. The non-MFC dll loads before MFC dll and if there is any data not freed before MFC exits, MFC falsely reports this as a memory leak. This is a [known issue](http://comments.gmane.org/gmane.comp.lib.opencv/43423) which is a problem when using opencv with mfc. The solution is to:

1. Static link MFC library (most common way)
2. Try the workaround to force mfc dll to be loaded first in the link above
3. Delay loading dlls as seen in [this question](https://stackoverflow.com/questions/9232837/how-to-remove-memory-leaks-between-opencv-1-1-and-mfc-6-0-without-linking-mfc-as).
I've noticed in the debug version that the combination of MFC and OpenCV can also result in strange behavior when you additionally use fopen and fread. fread might return error 9 (The storage control block address is invalid). 

Again, delayed loading the OpenCV dlls might solve the problem.