I work on a custom container and I manually allocate some heap memory:
template<typename element_type> class MyClass{ element_type* m_data = nullptr; std::size_t rows, columns; // assume that they have been initialized inline MyClass(){ this->m_data = new element_type[(this->rows)*(this->columns)]{}; this->m_data_end = this->m_data+(this->rows)*(this->columns); } }; When I perform an analysis of my code, XCode (and LLVM-Clang under the hood) tells me that this->m_data = new element_type[(this->rows)*(this->columns)]{}; is storing garbage value (uninitialized values). I don't understand what I am doing wrong with this example. Any clarification would be much appreciated.
To me, I was doing what was advised in this accepted answer: https://stackoverflow.com/a/67967472/23051105.
As requested by the comments, I will provide more details on the implementation:
template<typename element_type> class Parent{ std::size_t rows, columns; element_type* m_data = nullptr; element_type* m_data_end = nullptr; inline Parent(const std::size_t rows, const std::size_t columns) : rows(rows), columns(columns){} }; template<typename element_type> class MyClass : public Parent<element_type> { inline void createInternStorage(){ if (this->m_data != nullptr || this->m_data_end != nullptr) this->deleteInternStorage(); this->m_data = new element_type[(this->rows)*(this->columns)]{}; this->m_data_end = this->m_data+(this->rows)*(this->columns); } inline void deleteInternStorage(){ if (this->m_data != nullptr) delete[] this->m_data; this->m_data = nullptr; this->m_data_end = nullptr; } inline MyClass(const std::size_t rows, const std::size_t columns) : Parent<element_type>(rows, columns) { this->createInternStorage(); } }; Please keep in mind that the program is fully operational, it initializes the right amount of memory and everything appears to me totally fine. I'm just confused with this analyzer message.
rowandcolumnsare remain uninitialized. And you're using those unitialized variables in(this->rows)*(this->columns)leading to undefined behavior.rowsandcolumnsbefore using them? I presume by theassume that they have been initializedthere is some initialisation code somewhere that you've omitted? Is there a path through your code where they aren't initialised?std::size_t rows, columns;tostd::size_t rows{}, columns{};... did the problem go away?element_type.mainfunction which calls the relevant code in a way that reproduces the error. Also please state the exact commands you are using to do the analysis, and the versions of the compiler and analysis tools that you are using, as well as the exact text of the warning they report.