c++ - 为什么我不能删除这个数组元素的指针值?

标签 c++ arrays pointers

我有一个函数应该删除动态指针数组中的元素。

我已经构建了一个动态创建此数组的函数,它似乎工作正常(如果您发现任何问题,请告诉我)。

但是,我的删除函数不会让我删除 student[i] 处的值,特别是第 137 行。代码在注释掉这一行的情况下编译正常,但需要删除该值或否则会导致内存泄漏。

为什么我不能像在第 137 行那样调用 delete student[i]?问题是什么?我正在努力学习,希望得到一个简化的答案。

这是我的代码:

#include <iostream>
#include <cstring>
#include <string> //TESTING
#include <fstream> //needed to use files (contains definitions for ifstream and ofstream)
#include <stdlib.h>  //for exit 
#include <cctype> //char handling functions
#include <iomanip> //setprecision ,etc
#include <cstddef>

using namespace std;

const int SIZE = 101; //max size of arrays 

struct Student
{
   char *     name;
   float      gpa;
};

Student ** createStudentList(char ** names, int size);
bool destroyStudentList(Student ** studentList, int size);

int main ()
{
        Student ** studentList;

        char ** names;
        int size = 0;

        names = new char*[3];
        names[size] = new char[strlen("Lindsay")+1];
        strcpy(names[size], "Lindsay");
        size++;
        names[size] = new char[strlen("Emily") +1 ];
        strcpy(names[size], "Emily");
        size++;

        studentList = createStudentList(names, size);
        cout << "//TESTING: before destroyStudentList()" << endl;
        destroyStudentList(studentList, size);

        return 0;
}


//  The function creates an array of pointers to Student objects dynamically. 
//It allocates Student objects and set their name as the passed in “names” and gpa as 0. “size” is the number of “names” available.
// You can allocate 2*size as many pointers to Student objects just in case you need to add more to the list. 
//For the extra spots in the array, set them to nullptr. The function returns the pointer to the Student pointer array.
Student ** createStudentList(char ** names, int size)
{
        // code adapted from CS162 module 8 discussion post  for Lab 6 (Nancy Chan and Li Liang)

        int double_size = size *2;

        Student ** studentList = new Student * [double_size];

        Student * studentPtr = new Student [double_size];


        for (int i = 0; i < 2 * size; i++)
        {
                studentList[i] = &studentPtr[i];
        }


        for (int i = 0; i < size; i++)
        {
                studentList[i]->name = new char[strlen(names[i]) + 1];
                strcpy(studentList[i]->name, names[i]);
                studentList[i]->gpa = 0;

        }

        for (int i = size; i < double_size; i++)
        {
                studentList[i] = NULL;
        }

        return studentList;

}


//  The function deletes all the Student objects in the array along with their dynamically allocated data members, 
// such as name. It also releases the array of the pointers to the Student objects.  
// The function returns true if the operation is successful and false if “studentList” contains nullptr.
bool destroyStudentList(Student * studentList[], int size)
{
        int double_size = size *2;

         // When the pointer is nullptr, there is nothing to delete
        if (studentList == nullptr)
        {
                return false;
        }
        else
        {
                //cout << "//TESTING: in destroyStudentList. Else..." << endl;
                for (int i = 0; i < double_size; i++)
                {
                        if (studentList[i] != NULL) {
                        cout << (*studentList[i]).name << endl;
                        delete [] (*studentList[i]).name;/////can't delete the char array here
                        cout << "//TESTING1: delete [] studentList[i]->name;" << endl;

                        (*studentList[i]).name = NULL;
                        cout << "//TESTING2: studentList[i]->name = NULL;" << endl;

                        delete studentList[i];////////////WHY DOES THIS CAUSE AN EXCEPTION?
                        //cout << "//TESTING3: delete studentList[i];" << endl;
                        //
                        //studentList[i] = NULL;
                        //cout << "//TESTING4: studentList[i] = NULL;" << endl;
                        }
                }
        }
        delete studentList;
        studentList = nullptr;
        return true;

}

最佳答案

你问:

delete studentList[i];////////////WHY DOES THIS CAUSE AN EXCEPTION?

在我回答为什么那条线不好之前,让我从一个简单的例子开始。 如果你分配内存:

int* ip = new int[10];

释放内存的唯一有效方法是使用:

delete [] ip;

以下都是尝试释放该内存的无效方法。

delete ip;
delete [] ip+2;
delete [] ip+4;
delete ip+2;
delete ip+4;
delete &ip[2];
delete &ip[4];

线

delete studentList[i];

遇到了这个问题。您不仅没有使用 delete 运算符的数组形式,而且还对使用一次调用分配的数组中的单个元素调用 delete

createStudentList 中,您使用以下方法为 Student 数组分配了内存:

 Student * studentPtr = new Student [double_size];

然后使用以下方法将这些指针分配给 studentList:

   for (int i = 0; i < 2 * size; i++)
   {
      studentList[i] = &studentPtr[i];
   }

删除 Student 数组的唯一有效方法是使用:

delete [] studentList[0];

关于c++ - 为什么我不能删除这个数组元素的指针值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28802210/

相关文章:

c++ - 位域的完美转发解决方法

c++ - 你应该如何防御?

c++ - 解释从函数中通过引用返回数组的语法

python - BytesIO 流到 Numpy 数组? (摄影机)

javascript - 如果条件vue js,如何删除数组中的许多数据

pointers - go - 修改指向 slice 的指针不会修改原始指针

C++ 二进制操作数无效

c++ - 将带有可变参数模板参数的 std::tuple 作为其元素类型传递给另一个函数作为参数列表

c++ - 智能指针 - 程序终止时的段错误

c++ - 指向 int 的指针。 C++