Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 721
Patryk Avatar asked Jun 02 '26 21:06

Patryk


2 Answers

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, "");
like image 117
Daniel Marjamäki Avatar answered Jun 04 '26 12:06

Daniel Marjamäki


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.

like image 44
Wyzard Avatar answered Jun 04 '26 11:06

Wyzard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!