MCPcopy Create free account
hub / github.com/cppcheck-opensource/cppcheck / getAllocationType

Method getAllocationType

lib/checkmemoryleak.cpp:49–144  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

47
48
49CheckMemoryLeakImpl::AllocType CheckMemoryLeakImpl::getAllocationType(const Token *tok2, nonneg int varid, std::list<const Function*> *callstack) const
50{
51 // What we may have...
52 // * var = (char *)malloc(10);
53 // * var = static_cast<char *>(malloc(10));
54 // * var = new char[10];
55 // * var = strdup("hello");
56 // * var = strndup("hello", 3);
57 if (tok2 && tok2->str() == "(") {
58 tok2 = tok2->link();
59 tok2 = tok2 ? tok2->next() : nullptr;
60 }
61 if (tok2 && tok2->isCpp() && tok2->isKeyword() && endsWith(tok2->str(), "_cast"))
62 tok2 = tok2->astParent()->next();
63 if (!tok2)
64 return No;
65 if (tok2->str() == "::")
66 tok2 = tok2->next();
67 while (Token::Match(tok2, "%name% :: %type%"))
68 tok2 = tok2->tokAt(2);
69 if (!tok2->isName())
70 return No;
71
72 if (!Token::Match(tok2, "%name% . %type%")) {
73 // Using realloc..
74 AllocType reallocType = getReallocationType(tok2, varid);
75 if (reallocType != No)
76 return reallocType;
77
78 if (tok2->isCpp() && tok2->str() == "new") {
79 if (tok2->strAt(1) == "(" && !Token::Match(tok2->next(),"( std| ::| nothrow )"))
80 return No;
81 if (tok2->astOperand1() && (tok2->astOperand1()->str() == "[" || (tok2->astOperand1()->astOperand1() && tok2->astOperand1()->astOperand1()->str() == "[")))
82 return NewArray;
83 const Token *typeTok = tok2->next();
84 while (Token::Match(typeTok, "%name% :: %name%"))
85 typeTok = typeTok->tokAt(2);
86 const Scope* classScope = nullptr;
87 if (typeTok->type() && (typeTok->type()->isClassType() || typeTok->type()->isStructType() || typeTok->type()->isUnionType())) {
88 classScope = typeTok->type()->classScope;
89 } else if (typeTok->function() && typeTok->function()->isConstructor()) {
90 classScope = typeTok->function()->nestedIn;
91 }
92 if (classScope && classScope->numConstructors > 0)
93 return No;
94 return New;
95 }
96
97 if (mSettings.hasLib("posix")) {
98 if (Token::Match(tok2, "open|openat|creat|mkstemp|mkostemp|socket (")) {
99 // simple sanity check of function parameters..
100 // TODO: Make such check for all these functions
101 const int num = numberOfArguments(tok2);
102 if (tok2->str() == "open" && num != 2 && num != 3)
103 return No;
104
105 // is there a user function with this name?
106 if (tok2->function())

Callers

nothing calls this directly

Calls 15

numberOfArgumentsFunction · 0.85
ismemoryFunction · 0.85
nextMethod · 0.80
astParentMethod · 0.80
astOperand1Method · 0.80
typeMethod · 0.80
isClassTypeMethod · 0.80
isStructTypeMethod · 0.80
isUnionTypeMethod · 0.80
getAllocIdMethod · 0.80
deallocIdMethod · 0.80
endsWithFunction · 0.70

Tested by

no test coverage detected