【问题标题】:warning: deleting array "......." munmap_chunk(): invalid pointer Command terminated by signal 6警告:删除数组“.......” munmap_chunk():无效指针 命令由信号 6 终止
【发布时间】:2021-11-02 17:29:47
【问题描述】:

目前,我正在尝试学习和使用这个程序中的析构函数。我创建了一个名为 Student 的类,它可以获取 3 个科目的卷号、姓名和分数,并将其存储在一个数组中。我无法删除为存储学生成绩而创建的数组...

我收到一条错误/警告消息...

在析构函数中'Student::~Student()': :65:14: 警告:删除数组 '((学生*)this)->学生::标记' 65 |删除[] 标记; | ^~~~~ munmap_chunk(): 无效指针 命令被信号 6 终止

#include<iostream>
using namespace std;

//This class gets rollNo, name, marks for 3 subjects....
class Student
{
    private:
        int rollNumber;
        string name;
        int marks[3];
        
    public:
        
        void setRollnumber(int roll)
        {
            rollNumber = roll;
        }
        
        void setName(string name)
        {
            this->name = name;
        }
        
        void setMarks(int marks1, int marks2, int marks3)
        {
            this -> marks[0] = marks1;
            this -> marks[1] = marks2;
            this -> marks[2] = marks3;
        }
        
        int totalMarks();
        
        char grade(int totalMarks, int maxMarks);
        
        ~Student();
        
};
//Finds the total marks...
int Student :: totalMarks()
{
    int total = 0;
    
    for(int i=0; i<3; i++)
    {
        total += marks[i];
    }
    
    return total;
    
}
//Returns the grade...
char Student :: grade(int totalMarks, int maxMarks)
{
    float percent = ((float)totalMarks / (float)maxMarks) * 100;
    
    char grade;
    grade = percent >= 90 ? 'A' : (percent >= 75) ? 'B' : (percent >= 50) ? 'C' : 'F';
    
    return grade;
}

//Destructor....
Student :: ~Student()
{
    delete &rollNumber;
    delete &name;
    delete[] marks; 
}

int main(){
    
    Student bee;
    
    bee.setRollnumber(50);
    bee.setName("Bee");
    bee.setMarks(90, 80, 70);
    
    int total_marks_scored = bee.totalMarks();
    
    cout<<"Total Marks    : "<<total_marks_scored<<endl;
    cout<<"Grade Obtained : "<<bee.grade(total_marks_scored, 300);
    
    return 0;
    
}

【问题讨论】:

  • 你没有new他们。你为什么delete他们?

标签: c++ class oop destructor


【解决方案1】:

delete 用于释放通过调用new 在堆上动态分配的内存。 delete[]new[]也是如此。

您没有动态分配任何内存,因此您不需要释放它。在这种情况下,您不需要析构函数。

您也不要在删除调用中使用 &。

如果你想保留析构函数,因为你说你正在学习,那么你需要通过调用 new 为你的类成员分配内存,但成员需要是指针......

private:
        int* rollNumber;
        string* name;
        int* marks;

并使用 new 为它们分配内存,最好在构造函数中。

Student::Student() : 
    rollNumber(new int(0)),
    name(new string("")),
    marks(new int[3]))
{}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-04
    • 2018-08-23
    • 2016-08-08
    • 2014-05-14
    • 1970-01-01
    • 2011-08-09
    • 2020-08-04
    • 1970-01-01
    相关资源
    最近更新 更多