Main Content

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
In the preceding code, 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

expand all

#include <string_view>
#include <string>

extern std::string getString();

extern void useStringView(std::string_view s);

void foo()
{
    std::string_view sv = getString();

    useStringView(sv);
}

In this example, the std::string_view object sv is initialized by the temporary object returned by getString. The temporary goes out of scope at the end of the initialization statement. The function useStringView() is called with a dangling std::string_view. This call might result in unexpected behavior. Polyspace raises a defect on the initialization statement.

Correction — Use Named Variables When Initializing std::string_view

To fix this defect, initialize std::string_view objects by using named variables.

#include <string_view>
#include <string>

extern std::string getString();

extern void useStringView(std::string_view s);

void foo()
{
	const std::string s = getString();
	std::string_view sv = s;  
	useStringView(sv);
}

Result Information

Group: Programming
Language: C++
Default: Off
Command-Line Syntax: DANGLING_STRING_VIEW
Impact: High

Version History

Introduced in R2022b