In his post, Charles says
This C++ program compiled with /clr sums up what I don't like about Managed C++. It runs without complaint even though the buffer overrun is corrupting both allocated memory and unallocated memory, deallocated memory is accessed (admittedly the latter problem is trapped in the debug build but problems often occur only when running in released code), and an unitialized variable is used. A couple of people I've discussed this with are surprised that IL can access unmanaged types so I've included the output from ILDASM below.
void main(void) { char* buff1 = new char[16]; char* buff2 = new char[16]; for (int i = 0; i < 33; i++) buff1[i] = i; delete buff1; int x; *buff1 = x; }
Umm, there is nothing managed about this "Managed C++" program and thus you will not get any of the CLR benefits. I think you may be confused about Managed C++ and this is common. As I say in my book, in Chapter 7, compiling with /clr will not make *any* of your data managed. It just changes compilation to emit IL in an assembly. All of the data is *still unmanaged* and coming from the unmanaged heap. That's why you have the problems above. Only the types you specifically mark with __gc or __value will become managed and the problems will go away.
Do this and it won't run:
#include "stdafx.h"
#using <mscorlib.dll>
#include <tchar.h>
using namespace System;
// This is the entry point for this application
int _tmain(void)
{
// TODO: Please replace the sample code below with your own.
// char* buff1 = new __gc char[16];
char *buff1 = __gc new char[16];
char *buff2 = __gc new char[16];
for (int i = 0; i < 33; i++)
buff1[i] = i;
delete buff1;
int x;
*buff1 = x;
return 0;
}
11:12:15 PM
|