提问者:小点点

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


这段代码编译并运行,创建预期的输出,除了运行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;
}

共1个答案

匿名用户

一般来说---避免手动内存管理,为什么不直接使用std::string呢?

关于守则中的问题。

这部分代码是一个大大的no no:

        if (name == nullptr || strlen(name) <= 0 || dob > 2020 || power <= 0)
        {
            *this = Saiyan();   // Calls constructor that creates default.
        }

这里实际上绕过了析构函数,所以如果初始化了m_name,就会泄漏内存。

另一个问题出现在这个构造函数中:

    Saiyan::Saiyan(const char* name, int dob, int power)
    {
        set(name, dob, power);
    }

您没有确保对象在调用此构造函数后始终处于良好状态。

最后但并非最不重要的是,这里:

            if (m_name != nullptr && strlen(name) == 0)
            {
                delete[] m_name;
                m_name = nullptr;
            }

只有在新名称短的情况下才释放m_name,但无论新名称的长度如何,都应该释放m_name,因为无论新名称的长度如何,您都将新值设置为m_name。

同样,在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() {};
...