Patryk
Patryk

Reputation: 24092

Cppcheck saying that char[256] should be initialized in constructor's initializer list

I have checked my code with cppcheck and it says that my char outStr[256] field should be initialized in constructor's initializer list.

warning: Member variable 'outStr' is not initialized in the constructor.

This field is only used in this method:

const char* toStr(){
    sprintf(outStr,"%s %s", id.c_str(), localId.c_str());
    return outStr;
}

Is it better to add c("") to initializer list? Or cppcheck is wrong? Or there is other way to go around it?

Upvotes: 3

Views: 2577

Answers (3)

Daniel Marjamäki
Daniel Marjamäki

Reputation: 3037

I am a Cppcheck developer.

that cppcheck warning is written for all data members that are not initialized in the constructor. no matter how/if the members are used later.

to fix the warning you can initialize your array in the constructor. It's enough to initialize the first element. For example, add this in your constructor:

outStr[0] = 0;

or if you like that better:

sprintf(outStr, "");

Upvotes: 6

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

CppCheck is being a little over-zealous. But you can shut it up and help prevent accidents by initialising that member, if you're using C++11 and if you don't mind the overhead (which is minimal or even negligible unless constructing this object is in a really performance-critical part of your application).

Upvotes: 2

Wyzard
Wyzard

Reputation: 34563

I'd avoid having that field in the class to begin with. Using sprintf into a fixed-size buffer is unsafe (what if the output is more than 255 characters long?) and it's awkward to have the array exist for the entire lifetime of the object just so that it still exists when the toStr function returns.

Consider changing toStr to return a std::string object instead. That makes its implementation simpler — return id + ' ' + localId — and the string object will automatically allocate enough memory to hold the result of the concatenation. In code that calls toStr, you can call .c_str() on the returned string if you really need a raw character array.

Upvotes: 4

Related Questions