Patrik Valkovič
Patrik Valkovič

Reputation: 724

Control accessing to memory in Visual Studio

I am loking for free tool to Visual Studio 2015, which could control accessing to memory. I found just this article (https://msdn.microsoft.com/en-us/library/e5ewb1h3%28v=vs.90%29.aspx?f=255&MSPPError=-2147217396), which controls just memory leaks - its fine, but not enought. When I create array, and access out of that array, I need to know it. For example this code:

int* pointer = (int*)malloc(sizeof(int)*8);
for (int a = 0;a <= 8;a++)
    std::cout << *(pointer+a) << ' ';
free(pointer);
_CrtDumpMemoryLeaks();

This example will not throw exception, but still it access to memory, which is out of allocated space. Is tool for Visual Studio 2015, which will tell mi about it? Something like valgrind.
Thank you.

Upvotes: 0

Views: 531

Answers (1)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

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.

Upvotes: 1

Related Questions