cppcheck stops analysis of whole file when array of struct is declared - c++

I am running static code analysis using cppcheck.
I have a cpp source file which as bugs like "null pointer dereferenced" etc.
There is a piece of code in file. A structure is declared inside a class
class Example{
public:
typedef struct {
int num;
}MyStruct;
};
When array of structure is declared
Example::MyStruct st_arr[5];
Cppcheck stops the analysis as soon as it reaches this code and doesn't go further and report other bugs in file.
But if I simply declare a struct variable
Example::MyStruct st;
It goes fine.
So, the cppcheck stops the analysis when array of struct (declared in a class) is created.
Is this a issue with cppcheck?

I am a Cppcheck developer.
I see such weird behaviour also. It is not by intention. I will investigate.
Best regards,
Daniel Marjamäki

Most static analysis tools can be configured to not report errors from library headers. You probably have to configure cppcheck to recognize the headers, e.g. by defining paths which are treated as library files. They also usually parse special comments in the source code which can be used to suppress errors in regions of code, e.g. suppress errors before the include and then re-enable afterwards. How this works is described in the documentation of the tools.
These tools also have the ability to define suppressions to discard errors, e.g. false positives. This can also be used to suppress errors from third-party code.
The cppcheck manual chapters "Chapter 8. Suppressions" and "Chapter 9. Library configuration" should explain how to do this. If you have specific problems with the configuration you can post more detailed questions.

Related

How to find if a function is present in a cpp file using cppcheck?

I wanted to find whether the cpp file has a certain function implemented.
For example if a() is present in the cpp file. How do I write a rule for this? I want it throw exception, if it is not present.
static code analysis tools are not used to find the compile or linking errors.
If the 'a` function or method is not declared and defined the compiler or linker will inform you - you will get an error.
If the CppCheck can't detect this kind of check, you can try CppDepend and its code query language CQLinq to create your custom rules.
from file in Files where file.ChildMethods.Where(m=>m.Name=="a").Count()==0 select file
I am a Cppcheck developer.
Cppcheck has "rules" and "addons". A "rule" is executed by "--rule". With a "rule" you cannot check this as far as I see.
With an "addon" you can definitely implement this. A good start is to loop through the scope list. If you see a function scope for "a()" you can see where the scope body is.
You can read more about addons in the cppcheck manual. http://cppcheck.sourceforge.net/manual.pdf
Chapter 12.

How can I find all places a given member function or ctor is called in g++ code?

I am trying to find all places in a large and old code base where certain constructors or functions are called. Specifically, these are certain constructors and member functions in the std::string class (that is, basic_string<char>). For example, suppose there is a line of code:
std::string foo(fiddle->faddle(k, 9).snark);
In this example, it is not obvious looking at this that snark may be a char *, which is what I'm interested in.
Attempts To Solve This So Far
I've looked into some of the dump features of gcc, and generated some of them, but I haven't been able to find any that tell me that the given line of code will generate a call to the string constructor taking a const char *. I've also compiled some code with -s to save the generated equivalent assembly code. But this suffers from two things: the function names are "mangled," so it's impossible to know what is being called in C++ terms; and there are no line numbers of any sort, so even finding the equivalent place in the source file would be tough.
Motivation and Background
In my project, we're porting a large, old code base from HP-UX (and their aCC C++ compiler) to RedHat Linux and gcc/g++ v.4.8.5. The HP tool chain allowed one to initialize a string with a NULL pointer, treating it as an empty string. The Gnu tools' generated code fails with some flavor of a null dereference error. So we need to find all of the potential cases of this, and remedy them. (For example, by adding code to check for NULL and using a pointer to a "" string instead.)
So if anyone out there has had to deal with the base problem and can offer other suggestions, those, too, would be welcomed.
Have you considered using static analysis?
Clang has one called clang analyzer that is extensible.
You can write a custom plugin that checks for this particular behavior by implementing a clang ast visitor that looks for string variable declarations and checks for setting it to null.
There is a manual for that here.
See also: https://github.com/facebook/facebook-clang-plugins/blob/master/analyzer/DanglingDelegateFactFinder.cpp
First I'd create a header like this:
#include <string>
class dbg_string : public std::string {
public:
using std::string::string;
dbg_string(const char*) = delete;
};
#define string dbg_string
Then modify your makefile and add "-include dbg_string.h" to cflags to force include on each source file without modification.
You could also check how is NULL defined on your platform and add specific overload for it (eg. dbg_string(int)).
You can try CppDepend and its CQLinq a powerful code query language to detect where some contructors/methods/fields/types are used.
from m in Methods where m.IsUsing ("CClassView.CClassView()") select new { m, m.NbLinesOfCode }

Changing global variable names

I working on a huge code base written many years ago. We're trying to implement multi-threading and I'm incharge of cleaning up global variables (sigh!)
My strategy is to move all global variables to a class, and then individual threads will use instances of that class and the globals will be accessed through class instance and -> operator.
In first go, I've compiled a list of global variables using nm by finding B and D group object names. The list is not complete, and incase of static variables, I don't get file and line number info.
The second stage is even more messy, I've to replace all globals in the code base with classinstance->global_name pattern. I'm using cscope Change text string for this. The problem is that in case of some globals, their name is also being used locally inside functions, and thus cscope is replacing them as well.
Any other way to go about it? Any strategies, or help please!
just some suggestions, from my experience:
use eclipse: the C++ indexer is very good, and when dealing with a large project I find it very useful to track variables. shift+ctrl+g (I have forgotten how to access to it from menus!) let you search all the references, ctrl+alt+h (open call hierarchy) the caller-callee trees...
use eclipse: it has good refactoring tools, that is able to rename a variable without touching same-name-different-scope variables. (it often fails in case there are templates involved. I find it good, better than visual studio 2008 counterpart).
use eclipse: I know, it get some time to get started with it, but after you get it, it's very powerful. It can deal easily with the existing makefile based project (file -> new -> project -> makefile project with existing code).
I would consider not to use class members, but accessors: it's possibile that some of them will be shared among threads, and need some locking in order to be properly used. So I would prefer: classinstance->get_global_name()
As a final note, I don't know whether using the eclipse indexer at command-line would be helpful for your task. You can find some examples googling for it.
This question/answer can give you some more hints: any C/C++ refactoring tool based on libclang? (even simplest "toy example" ). In particular I do quote "...C++ is a bitch of a language to transform"
Halfway there: if a function uses a local name that hides the global name, the object file won't have an undefined symbol. nm can show you those undefined symbols, and then you know in which files you must replace at least some instances of that name.
However, you still have a problem in the rare cases that a file uses both the global name and in another function hides the global name. I'm not sure if this can be resolved with --ffunction-sections; but I think so: nm can show the section and thus you'll see the undefined symbols used in foo() appear in section .text.foo.

flycheck cppcheck stop checking unusedStructMember

So I've recently begun using flycheck within emacs. Overall it's working great, but I've been having a small issue with flycheck using cppcheck in c++ mode. I'm getting a bunch of unusedStructMember warnings, likely due to not using that member within the present file. I was wondering if it is possible to tell flycheck to disable the unusedStructMember warnings from cppcheck, and if so, how would I go about doing so? My emacs-lisp skills are mostly non-existent and so far I haven't found anyone with a similar problem.
Thanks!
This is not an emacs configuration but something depends on the backend you use for C++ flycheck (i.e. cppcheck).
I just took a look at the manual of cppcheck. Obviously you can do it by inline pragmas. For example:
void f() {
char arr[5];
// cppcheck-suppress arrayIndexOutOfBounds
arr[10] = 0;
}
In your case, you'll need something like:
// cppcheck-suppress unusedStructMember

Tools for finding unused function declarations?

Whilst refactoring some old code I realised that a particular header file was full of function declarations for functions long since removed from the .cpp file. Does anyone know of a tool that could find (and strip) these automatically?
You could if possible make a test.cpp file to call them all, the linker will flag the ones that have no code as unresolved, this way your test code only need compile and not worry about actually running.
PC-lint can be tunned for dedicated purpose:
I tested the following code against for your question:
void foo(int );
int main()
{
return 0;
}
lint.bat test_unused.cpp
and got the following result:
============================================================
--- Module: test_unused.cpp (C++)
--- Wrap-up for Module: test_unused.cpp
Info 752: local declarator 'foo(int)' (line 2, file test_unused.cpp) not referenced
test_unused.cpp(2) : Info 830: Location cited in prior message
============================================================
So you can pass the warning number 752 for your puropse:
lint.bat -"e*" +e752 test_unused.cpp
-e"*" will remove all the warnings and +e752 will turn on this specific one
If you index to code with Doxygen you can see from where is each function referenced. However, you would have to browse through each class (1 HTML page per class) and scan for those that don't have anything pointing to them.
Alternatively, you could use ctags to generate list of all functions in the code, and then use objdump or some similar tool to get list of all function in .o files - and then compare those lists. However, this can be problematic due to name mangling.
I don't think there is such thing because some functions not having a body in the actual source tree might be defined in some external library. This can only be done by creating a script which makes a list of declared functions in a header and verifies if they are sometimes called.
I have a C++ ftplugin for vim that is able is check and report unmatched functions -- vimmers, the ftplugin suite is not yet straightforward to install. The ftplugin is based on ctags results (hence its heuristic could be easily adapted to other environments), sometimes there are false positives in the case of inline functions.
HTH,
In addition Doxygen (#Milan Babuskov), you can see if there are warnings for this in your compiler. E.g. gcc has -Wunused-function for static functions; -fdump-ipa-cgraph.
I've heard good things about PC-Lint, but I imagine it's probably overkill for your needs.