You can replace the given Microsoft'ish code
int* pointer = (int*)malloc(sizeof(int)*8);
for (int a = 0;a <= 8;a++)
std::cout << *(pointer+a) << ' ';
free(pointer);
_CrtDumpMemoryLeaks();
… with this:
{
vector<int> v( 8 );
for( i = 0; i <= 8; ++i )
{
cout << v.at( i ) << ' ';
}
}
_CrtDumpMemoryLeaks();
And since there's no point in checking for memory leaks in that code (indeed the exception from the attempt to access v[8]
ensures that the _CrtDumpMemoryLeaks()
statement is not executed), you can simplify it to just
vector<int> v( 8 );
for( i = 0; i <= 8; ++i )
{
cout << v.at( i ) << ' ';
}
Now, it's so long since I've been checking for indexing errors etc. that I'm no longer sure of the exact magic incantations to add checking of ordinary []
indexing with g++ and Visual C++. I just remember that one could, at least with g++. But anyway, the practical way to go about things is not to laboriously check indexing code, but rather avoid manual indexing, writing
// Fixed! No more problems! Hurray!
vector<int> v( 8 );
for( int const value : v )
{
cout << value << ' ';
}
About the more general aspect of the question, how to ensure that every invalid memory access generates a trap or something of the sort, that's not generally practically possible, because the granularity of memory protection is a page of memory, which in the old days of Windows was 4 KB (imposed by the processor's memory access architecture). It's probably 4 KB still. There would just be too dang much overhead if every little allocation was rounded up to 4K with a 4K protected page after that.
Still I think it's done for the stack. That's affordable: a single case of great practical utility.
However, the C++ standard library has no functionality for that, and I don't think Visual C++ has any extensions for that either, but if you really want to go that route, then check out the Windows API, such as VirtualAlloc
and friends.