### Crashing Code

The following code makes my program crash (program exits) by heap corruption when the third line (the 'delete' command) is called:

```
1: CStringArray* pStringArray = new CStringArray();
2: ClassInDll::addToStringArray(_T("asdf"), *pStringArray);
3: delete pStringArray;

```

with

```
1: ClassInDll::addToStringArray(CString s, CStringArray& sa){
2:  sa.Add(s);
3: }

```

addToStringArray() is static

* Be aware that this is not actually my code, but simply the minimum with which I can reproduce the error. It is reproducible with CArray<CString> as well.
* I verified, that the heap corruption does indeed **not** happen **before** that code line via
`gflags /p /enable MyExe.exe /full`

StackTrace:

[![StackTrace](https://i.stack.imgur.com/N6CDT.png)](https://i.stack.imgur.com/N6CDT.png)

---

### What seems to be the problem

|  |  | Dll dependency | MFC source |
| --- | --- | --- | --- |
| 1 | CStringArray creation | MyExe.exe > MFC | ...\Microsoft Visual Studio 10.0\VC\atlmfc\src\mfc\array\_s.cpp |
| 2 | Internal array allocation | MyExe.exe > MyDll.dll > MFC | ...\Microsoft Visual Studio 10.0\VC\atlmfc\include\afxcoll.inl |
| 3 | Deletion | MyExe.exe > MFC | ...\Microsoft Visual Studio 10.0\VC\atlmfc\src\mfc\array\_s.cpp |

The fact that the internal array is not deleted the same way it was created is probably the error. (Please correct me if I'm wrong)

---

### Project Settings

I made sure that the same MFC settings are used in MyExe.exe as well as MyDll.dll, i.e.:

|  |  |
| --- | --- |
| Use of MFC | Use MFC in a Shared DLL |
| Use of ATL | Not using ATL |
| Character Set | Use Unicode Character Set |

I test in debug mode, so there is no optimization.

---

### Question

MyDll.dll is not the only dll that is loaded, and there is too much going on with project dependencies (to third party dlls etc), so I cannot make all this part of my question.

So my questions boil down to:

* Is my assumption correct that array\_s.cpp and afxcoll.inl are not compatible with one another?
* What makes one piece of code call array\_s.cpp, and the other call afxcoll.inl?
* What else could be the problem?

I have tried turning it off and on again ;)

Thank you in advance!

---

### Update

PaulMcKenzie pointed out that this is the case if I build against different CRTs which was the case. One was "Multithreaded Debug DLL", the other was "Multithreaded DLL". Still, the problem persists, after making both equal. [This page](https://learn.microsoft.com/en-us/cpp/c-runtime-library/potential-errors-passing-crt-objects-across-dll-boundaries?view=msvc-160) states that if using VS 2015 and above with Windows 10 and having project settings so that the same runtime library is used, the same CRT library is used at runtime (and therefore should use the same heap, right?).

I've made sure, that every entry within "Project Properties -> C/C++ -> Code Generation" is exactly the same in the exe and dll.