简体   繁体   中英

Static Analysis to detect Buffer Overrun on Visual Studio C++ 2012

Following code writes into invalid area in memory but there's no compilation error.

int _tmain(int argc, _TCHAR* argv[])
{
    char* s1 = new char[10];
    for(int i=0;i<20;i++) s1[i]='a';
    cout << s1 << endl;
    return 0;
}

In runtime the code terminates with return code 0 printing 20 a's then some garbage before it met 0 but I assume this is very dangerous as it could contaminate / illegally access other area in memory.

Is there any way such mistake can be detected in compile time? Or at least a runtime exception raised pointing straight into s1[i]='a' line?

Setting /RTCs and /GS flag as recommended in other posts did not help.

Running Visual Studio code analysis (ANALZYE -> Run Code Analysis) gives no result either.

There are list of tools third party tools posted in here: C++ static code analysis tool on Windows but I'm hoping there's a way this can be detected by Visual Studio alone?

According to http://msdn.microsoft.com/en-us/library/8dbf701c.aspx , /GS (Buffer Security Check) is carried out in run-time, not in compile type.

/RTCs (according to http://msdn.microsoft.com/en-us/library/8wtf2dfz.aspx ) controls run-time checks. So neither of these two switches were designed to do static analysis of your code. That's, they are not supposed to detect your problem at compile time.

I think static code analysis is still in research stage in general, I'd be surprised that VS 2012 would provide full fledged support.

Another possibility is that the specific types of error you are trying to detect is an array-out-of-bound error. Buffer-overrun may not be the right keyword to do search.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM