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

Function isDangerousTypeConversion

lib/checkother.cpp:291–327  ·  view source on GitHub ↗

@brief would it make sense to use dynamic_cast instead of C style cast? */

Source from the content-addressed store, hash-verified

289
290/** @brief would it make sense to use dynamic_cast instead of C style cast? */
291static bool isDangerousTypeConversion(const Token* const tok)
292{
293 const Token* from = tok->astOperand1();
294 if (!from)
295 return false;
296 if (!tok->valueType() || !from->valueType())
297 return false;
298 if (tok->valueType()->typeScope != nullptr &&
299 tok->valueType()->typeScope == from->valueType()->typeScope)
300 return false;
301 if (tok->valueType()->type == from->valueType()->type &&
302 tok->valueType()->isPrimitive())
303 return false;
304 // cast from derived object to base object is safe..
305 if (tok->valueType()->typeScope && from->valueType()->typeScope) {
306 const Type* fromType = from->valueType()->typeScope->definedType;
307 const Type* toType = tok->valueType()->typeScope->definedType;
308 if (fromType && toType && fromType->isDerivedFrom(toType->name()))
309 return false;
310 }
311 const bool refcast = (tok->valueType()->reference != Reference::None);
312 if (!refcast && tok->valueType()->pointer == 0)
313 return false;
314 if (!refcast && from->valueType()->pointer == 0)
315 return false;
316
317 if (tok->valueType()->type == ValueType::Type::VOID || from->valueType()->type == ValueType::Type::VOID)
318 return false;
319 if (tok->valueType()->pointer == 0 && tok->valueType()->isIntegral())
320 // ok: (uintptr_t)ptr;
321 return false;
322 if (from->valueType()->pointer == 0 && from->valueType()->isIntegral())
323 // ok: (int *)addr;
324 return false;
325
326 return true;
327}
328
329//---------------------------------------------------------------------------
330// For C++ code, warn if C-style casts are used on pointer types

Callers 2

Calls 4

astOperand1Method · 0.80
isDerivedFromMethod · 0.80
isIntegralMethod · 0.80
nameMethod · 0.45

Tested by

no test coverage detected