C++ CPP中的Valgrind和内存泄漏:“;条件跳转或移动取决于未初始化的值;

C++ CPP中的Valgrind和内存泄漏:“;条件跳转或移动取决于未初始化的值;,c++,memory,valgrind,C++,Memory,Valgrind,此代码编译并运行,创建预期的输出,除非运行valgrind,然后出现这些内存泄漏。以下代码在Visual Studio上运行,不会出现任何警告或错误 所以我的问题是,内存泄漏发生在哪里?我对CPP比较陌生,在这方面花了很多时间,所以这些错误让我大吃一惊 在顺序方面,我有没有做错什么?我是否在某处传递未初始化的值?困惑 我很难弄清楚失忆发生在哪里。以下是文件: /// Saiyan.cpp #define _CRT_SECURE_NO_WARNINGS #include <string.h

此代码编译并运行,创建预期的输出,除非运行valgrind,然后出现这些内存泄漏。以下代码在Visual Studio上运行,不会出现任何警告或错误

所以我的问题是,内存泄漏发生在哪里?我对CPP比较陌生,在这方面花了很多时间,所以这些错误让我大吃一惊

在顺序方面,我有没有做错什么?我是否在某处传递未初始化的值?困惑

我很难弄清楚失忆发生在哪里。以下是文件:

/// Saiyan.cpp

#define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <iostream>
#include "Saiyan.h"

using namespace std;

namespace sdds
{
    // CONSTRUCTORS:
    Saiyan::Saiyan()
    {
        // default state
        m_name = nullptr;   // Dynamic allocation:  set to nullptr!
        m_dob = 0;
        m_power = 0;
        m_super = false;
        m_level = 0;
    }
    
    Saiyan::Saiyan(const char* name, int dob, int power)
    {
        set(name, dob, power);
    }

    // MEMBER FUNCTIONS:
    void Saiyan::set(const char* name, int dob, int power, int level, bool super)
    {
        // Check if arguments are valid:
        if (name == nullptr || strlen(name) <= 0 || dob > 2020 || power <= 0)
        {
            *this = Saiyan();   // Calls constructor that creates default.
        }
        else
        {
            // Deallocate previosly allocated memory for m_name to avoid memory leak:
            if (m_name != nullptr && strlen(name) == 0)
            {
                delete[] m_name;
                m_name = nullptr;
            }
            // Assign validate values to current object:
            m_name = new char[strlen(name) + 1];
            strcpy(m_name, name);
            m_dob = dob;
            m_power = power;
            m_super = super;
            m_level = level;
        }
    }
    
    bool Saiyan::isValid() const
    {
        bool valid_state = m_name != nullptr && strlen(m_name) > 0 && m_dob < 2020 && m_power > 0;
        return valid_state;
    }

    void Saiyan::display() const
    {
        if (isValid())
        {
            cout << m_name << endl;
            
            cout.setf(ios::right);
            cout.width(10);
            cout << "DOB: " << m_dob << endl;
            cout.width(10);
            cout << "Power: " << m_power << endl;
            cout.width(10);
            if (m_super == true) {
                cout << "Super: " << "yes" << endl;
                cout.width(10);
                cout << "Level: " << m_level;
            }
            else
            {
                cout << "Super: " << "no";
            }
            cout.unsetf(ios::left);
        }
        else
        {
            cout << "Invalid Saiyan!";
        }
        cout << endl;
    }

    bool Saiyan::fight(Saiyan& other)
    {
        // Check both Saiyans for super level and power up accordingly:
        if (m_super == true)
        {
            m_power += int(m_power * (.1 * m_level));   // Cast an int to avoid possible memory loss.
        }
        if (other.m_super == true)
        {
            other.m_power += int(other.m_power * (.1 * other.m_level));
        }

        bool value = m_power > other.m_power;
        return value;
    }

    // DESTRUCTOR:
    Saiyan::~Saiyan()
    {
        if (m_name != nullptr)
        {
            delete[] m_name;    // Deallocate memory of member.
            m_name = nullptr;
        }
    }
}



// Saiyan.h

#pragma once
#ifndef SDDS_SAIYAN_H
#define SDDS_SAIYAN_H

namespace sdds
{
    class Saiyan
    {
        char* m_name;       // Dynamically allocated array of chars.
        int m_dob;          // Year the Saiyan was born.
        int m_power;        // Integer indicating the strength of the Saiyan (>= 0).
        bool m_super;       // indicates whether Saiyan can evolve
        int m_level;        // an integer indicating the level of a SS

        /*
        ***Valid Name*** : a dynamically allocated array of chars.
        ***Valid Year of Birth***: an integer within the interval[0, 2020].
        ***Valid Power***: an integer that is greater than 0.
        */

    public:
        Saiyan();
        Saiyan(const char* name, int dob, int power);  // Custom constructor
        void set(const char* name, int dob, int power, int level = 0, bool super = false);
        bool isValid() const;
        void display() const;
        bool fight(Saiyan& other);  // Fight and power up Saiyans.
        ~Saiyan();
    };
}

#endif



// main.cpp

#include <iostream>
#include "Saiyan.h"
#include "Saiyan.h"  // this is on purpose

using namespace std;
using namespace sdds;

void printHeader(const char* title)
{
    char oldFill = cout.fill('-');
    cout.width(40);
    cout << "" << endl;

    cout << "|> " << title << endl;

    cout.fill('-');
    cout.width(40);
    cout << "" << endl;
    cout.fill(oldFill);
}


int main()
{
    {
        printHeader("T1: Checking default constructor");

        Saiyan theSayan;
        theSayan.display();
        cout << endl;
    }

    {
        printHeader("T2: Checking custom constructor");

        Saiyan army[] = {
          Saiyan("Nappa", 2025, 1),
          Saiyan("Vegeta", 2018, -1),
          Saiyan("Goku", 1990, 200),
          Saiyan(nullptr, 2015, 1),
          Saiyan("", 2018, 5)
        };

        cout << "Only #2 should be valid:" << endl;
        for (int i = 0; i < 5; i++)
        {
            cout << "  Sayan #" << i << ": " << (army[i].isValid() ? "valid" : "invalid") << endl;
        }
        for (int i = 0; i < 5; i++)
        {
            army[i].display();
        }
        cout << endl;
    }

    // valid saiyans
    Saiyan s1("Goku", 1990, 2000);
    Saiyan s2;
    s2.set("Vegeta", 1989, 2200);

    {
        printHeader("T3: Checking the fight");
        s1.display();
        s2.display();

        cout << "S1 attacking S2, Battle " << (s1.fight(s2) ? "Won" : "Lost") << endl;
        cout << "S2 attacking S1, Battle " << (s2.fight(s1) ? "Won" : "Lost") << endl;
        cout << endl;
    }

    {
        printHeader("T4: Checking powerup");
        s1.set("Goku", 1990, 1900, 1, true);
        int round = 0;
        bool gokuWins = false;
        while (!gokuWins) // with every fight, the super saiyan should power up
        {
            cout << "Round #" << ++round << endl;
            gokuWins = s1.fight(s2);
            s1.display();
            s2.display();
        }

        cout << "Bonus round. Is s2 winning? " << (s2.fight(s1) ? "yes" : "no") << endl;
        s1.display();
        s2.display();
        cout << endl;
    }

    {
        printHeader("T5: Upgrading s2");
        s2.set("Vegeta", 1990, 2200, 3, true);

        cout << "Super Battle. Is s2 winning? " << (s2.fight(s1) ? "yes" : "no") << endl;
        s1.display();
        s2.display();
        cout << endl;
    }
 
    return 0;
}
///Saiyan.cpp
#定义\u CRT\u安全\u无\u警告
#包括
#包括
#包括“Saiyan.h”
使用名称空间std;
命名空间SDD
{
//建造商:
赛扬::赛扬()
{
//默认状态
m_name=nullptr;//动态分配:设置为nullptr!
m_dob=0;
m_幂=0;
m_super=假;
m_水平=0;
}
赛扬::赛扬(const char*name,int dob,int power)
{
设置(名称、dob、功率);
}
//成员职能:
void Saiyan::set(const char*name、int dob、int power、int level、bool super)
{
//检查参数是否有效:
如果(名称==nullptr | | strlen(名称)2020 | |功率0和m|u dob<2020和m|u功率>0;
返回有效的_状态;
}
void Saiyan::display()常量
{
if(isValid())
{
一般来说,避免手动内存管理,为什么不使用std::string呢

关于守则中的问题

这部分代码是一个很大的禁忌:

        if (name == nullptr || strlen(name) <= 0 || dob > 2020 || power <= 0)
        {
            *this = Saiyan();   // Calls constructor that creates default.
        }
调用此构造函数后,您无法确保对象始终处于良好状态

最后但并非最不重要的是:

            if (m_name != nullptr && strlen(name) == 0)
            {
                delete[] m_name;
                m_name = nullptr;
            }
仅当新名称较短时才取消分配m_名称,但无论新名称长度如何,都应取消分配,因为无论新名称长度如何,都要将新值设置为m_名称

此外,在C++11中,您可以为构造函数外部的成员提供默认值,并且这些值将在每个未显式设置不同值的构造函数中使用:

    class Saiyan
    {
        char* m_name = nullptr; // Dynamically allocated array of chars.
        int m_dob = 0;          // Year the Saiyan was born.
        int m_power = 0;        // Integer indicating the strength of the Saiyan (>= 0).
        bool m_super = false;   // indicates whether Saiyan can evolve
        int m_level = 0;        // an integer indicating the level of a SS

    public:
        Saiyan() {};
...
一般来说,避免手动内存管理,为什么不使用std::string呢

关于守则中的问题

这部分代码是一个很大的禁忌:

        if (name == nullptr || strlen(name) <= 0 || dob > 2020 || power <= 0)
        {
            *this = Saiyan();   // Calls constructor that creates default.
        }
调用此构造函数后,您无法确保对象始终处于良好状态

最后但并非最不重要的是:

            if (m_name != nullptr && strlen(name) == 0)
            {
                delete[] m_name;
                m_name = nullptr;
            }
仅当新名称较短时才取消分配m_名称,但无论新名称长度如何,都应取消分配,因为无论新名称长度如何,都要将新值设置为m_名称

此外,在C++11中,您可以为构造函数外部的成员提供默认值,并且这些值将在每个未显式设置不同值的构造函数中使用:

    class Saiyan
    {
        char* m_name = nullptr; // Dynamically allocated array of chars.
        int m_dob = 0;          // Year the Saiyan was born.
        int m_power = 0;        // Integer indicating the strength of the Saiyan (>= 0).
        bool m_super = false;   // indicates whether Saiyan can evolve
        int m_level = 0;        // an integer indicating the level of a SS

    public:
        Saiyan() {};
...
工作

工作


您可以将
Saiyan::~Saiyan(){if(m_name!=nullptr){delete[]m_name;m_name=nullptr;}}}
缩短为
Saiyan::~Saiyan(){delete[]m_name;}
您得到了完全相同的结果。
delete
ing a
nullptr
是不可操作的,在析构函数中将成员设置为
nullptr
是毫无意义的。您可以缩短
Saiyan::~Saiyan(){if(m_name!=nullptr){delete[]m_name;m_name=nullptr;}
to just
Saiyan::~Saiyan(){delete[]m_name;}
得到了完全相同的结果。
delete
ing a
nullptr
是不可操作的,在析构函数中将成员设置为
nullptr
是没有意义的。