Patrick
Patrick

Reputation: 1323

Is there any static checking tool to check buggy code like this

I wrote the some buggy code like this:

#include "stdafx.h"
#include <string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{

    string some_file = "afdfadf";

    if(true)
    {
        string some_file = "/"+ some_file;
    }

    return 0;
}

It will throw an exception when calling std::operator+.

I guess this is because in the if statement the second some_file is an uninitialized string.

Is there any static checking tool that can help find this kind of bug?

Upvotes: 3

Views: 276

Answers (4)

Patrick
Patrick

Reputation: 1323

I just tried, clang can help find the bug:

[~]$ clang bug.cpp 
bug.cpp:11:29: warning: variable 'some_file' is uninitialized when used within
      its own initialization [-Wuninitialized]
    string some_file = "/"+ some_file;
           ~~~~~~~~~        ^~~~~~~~~

Upvotes: 4

Jonathan Wakely
Jonathan Wakely

Reputation: 171253

GCC has a warning for that case:

$ g++ t.cc -Wshadow
t.cc: In function ‘int main(int, char**)’:
t.cc:11:16: warning: declaration of ‘some_file’ shadows a previous local [-Wshadow]
t.cc:7:12: warning: shadowed declaration is here [-Wshadow]

Upvotes: 3

Torsten Robitzki
Torsten Robitzki

Reputation: 2555

I was quit happy with using pclint. It will find this type of errors but it might take some time to configure it when used with an existing, larger code base.

Upvotes: 0

Arne Mertz
Arne Mertz

Reputation: 24576

Compilers can warn you about using a variable in its own initialization.

In GCC and CLANG, you can use -Winit-self I am not sure about MSVC, but compiling with /W4 might give you a warning about those, too.

Upvotes: 3

Related Questions