[英]Valgrind errors that i cant figure out
This is the valgrind error that occurs when i run the program.这是我运行程序时发生的 valgrind 错误。
==137479== Conditional jump or move depends on uninitialised value(s)
==137479== at 0x400B50: sdds::Ship::setShipEmpty() (Ship.cpp:25)
==137479== by 0x400AF2: sdds::Ship::Ship() (Ship.cpp:20)
==137479== by 0x401181: main (main_prof.cpp:49)
==137479==
==137479== Invalid write of size 1
==137479== at 0x40097A: sdds::Engine::setEmpty() (Engine.cpp:19)
==137479== by 0x400B3E: sdds::Ship::setShipEmpty() (Ship.cpp:26)
==137479== by 0x400AF2: sdds::Ship::Ship() (Ship.cpp:20)
==137479== by 0x401181: main (main_prof.cpp:49)
==137479== Address 0x1fff001018 is not stack'd, malloc'd or (recently) free'd
My program at the moment is static and not using dynamic memory allocation, The goal is to create a function to set the variables to a safe empty state. My program at the moment is static and not using dynamic memory allocation, The goal is to create a function to set the variables to a safe empty state. When the object is valid set it accordingly.
当 object 有效时进行相应设置。 Here are my functions from Ship.cpp.
这是我在 Ship.cpp 中的函数。 Similarly, engine.cpp function to set to an empty state is pretty much the same.
同样,engine.cpp function 设置为空 state 几乎相同。
Ship::Ship()
{
setShipEmpty();
}
void Ship::setShipEmpty()
{
m_type[0] = '\0';
for (int i = 0; i < m_engCnt; i++) {
m_engines[i].setEmpty();
m_engCnt = 0;
}}
Ship::Ship(const char* sType, const Engine* engines, int sizeOfEngine)
{
if (sType != nullptr && strlen(sType) > 0 && strlen(sType) < TYPE_MAX_SIZE && engines[0].get() > 0 && sizeOfEngine < 10)
{
strcpy(m_type, sType);
m_engCnt= sizeOfEngine ;
for (int i = 0; i < sizeOfEngine; i++) {
m_engines[i] = engines[i];
}}
else {
setShipEmpty();
}}
ship.h file船.h 文件
class Ship
{ ...private:
Engine m_engines[10];
char m_type[TYPE_MAX_SIZE+1];
int m_engCnt;
....
engine.h file引擎.h 文件
const int TYPE_MAX_SIZE = 30;
class Engine
{
double m_size;
char m_type[TYPE_MAX_SIZE+1];
public:...
engine.cpp引擎.cpp
void Engine::setEmpty()
{
m_type[0] = 0;
m_size = 0;
}
Engine::Engine()
{
setEmpty();
}
Engine::Engine (const char* type, double size)
{
setEmpty();
strcpy(m_type, type);
m_size = size;
}
Valgrind is complaining that you did not set a value for m_engCnt
yet you are using it in a for loop. Valgrind 抱怨您没有为
m_engCnt
设置值,但您在 for 循环中使用它。 Given that m_engines
is an Engine[10]
, I suppose you want that loop to just go from 0 to 10.鉴于
m_engines
是Engine[10]
,我想您希望该循环仅从 0 到 10 的 go 。
Two points for improvement:两点改进:
Engine
that does whatever setEmpty
does now.Engine
创建一个默认构造函数,该构造函数执行setEmpty
现在所做的任何事情。 That will allow you to skip the for loop in the Ship
constructor.Ship
构造函数中的 for 循环。std::vector<Engine>
so you don't have to manually initialize Engine
s at the start that you will never use.std::vector<Engine>
这样您就不必在开始时手动初始化您永远不会使用的Engine
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.