Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cppcheck warns about the pointer to local variable in list initialization

Tags:

c++

cppcheck

I analyzed some code with cppcheck for errors and code quality. I came across an error which I think is an false positive. The following code example shows the problem (marked with comment).

cppcheck - v 1.89

#include <string>
#include <vector>
#include <iostream>

std::string func() {
    std::vector<char> data{};
    data.push_back('a');
    data.push_back('b');
    data.push_back('c');
    return std::string{ data.data(), data.size() }; // error marked here
    // severity: error
    // line: 12
    // summary: Returning object that points to local variable 'data' that will be invalid when returning.
}

int main() {
    std::string ret{};
    {
        ret = func();
    }
    std::cout << ret << std::endl;
    return 0;
}

If i use () instead of {}, it resolves the error.

EDIT

When I debug the example with () or {}, there is totally no difference. I use Visual Studio 17 with C++14.

like image 510
skratchi.at Avatar asked Nov 14 '19 08:11

skratchi.at


2 Answers

I think the rule was for before C++11:

{/*..*/} was only use for aggregate initialization before C++11, so T{ data.data(), data.size() } could only store the future dangling pointer thus the diagnostic.

With T(data.data(), data.size() ), it is a regular constructor call, so it actually depends of T constructor, so no diagnostic can be safely be done without inspecting T constructor (and I doubt than cppcheck does inspect) (and BTW it is safe for std::string).

So indeed, it is a false positive.

like image 55
Jarod42 Avatar answered Nov 09 '22 07:11

Jarod42


It's a false-positive as the string ctor makes a copy of the passed char* string.

like image 2
demeter Avatar answered Nov 09 '22 06:11

demeter