Cppcheck says char [256] should be initialized in the constructor initializer list

I checked my code with cppcheck and it says my field char outStr[256]

should be initialized in the constructor 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 the initializer list? Or is cppcheck wrong? Or is there another way to get around it?

+3


source to share


3 answers


I am a Cppcheck developer.

that a 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. This is enough to initialize the first element. For example add this to your constructor:



outStr[0] = 0;

      

or if you like this:

sprintf(outStr, "");

      

+6


source


I would not use this field in a class. Using sprintf

a fixed size buffer is unsafe (what if the output is more than 255 characters long?), And it's inconvenient to have an array for the entire lifecycle of an object so that it still exists when the toStr

function returns.



Consider changing toStr

to return an object std::string

. This makes it easier to implement - return id + ' ' + localId

- and the string object automatically allocates enough memory to store the result of the concatenation. In the code that calls toStr

, you can call .c_str()

on the returned string if you really want a character array.

+4


source


CppCheck is a little overzealous. But you can close it and help prevent accidents by initializing this member if you are using C ++ 11 and if you don't mind the overhead (which is minimal or even negligible, unless the creation of this object is done, a critical part of your application ).

+2


source







All Articles