std::string_view initialized with dangling pointer
An std::string_view
object is initialized by using an unnamed
temporary object
Since R2022b
Description
This defect occurs when you construct an std::string_view
object by
using an unnamed temporary object.
std::string get(); std::string_view s = get(); // Defect
get()
returns a temporary string that goes out of scope
after the semicolon. The string_view
object s
remains in
scope, but it points to memory that is already released. Polyspace® flags initializing string_view
objects with such dangling
pointers.This defect is relevant for C++17 or later.
Risk
An std::string_view
object typically contains a pointer to a
const char
array. When you initialize an
std::string_view
object by using an unnamed temporary, the pointer in
the std::string_view
object points to the memory block containing the
temporary. The unnamed temporary goes out of scope at the end of the statement where it is
created, and releases the memory. The std::string_view
object then
contains a dangling pointer, which leads to bugs that are difficult to find.
Fix
Avoid using unnamed temporaries when initializing std::string_view
objects. Use named variables instead.
Examples
Result Information
Group: Programming |
Language: C++ |
Default: Off |
Command-Line Syntax:
DANGLING_STRING_VIEW |
Impact: High |
Version History
Introduced in R2022b
See Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)