ReeSSult
ReeSSult

Reputation: 496

Allocate and dellete array of pointers

Given the following struct declaration:

struct Student

{

   char *     name;

   float      gpa;

}

Implement the following functions:

Student ** createStudentList(char ** names, int size);

The above 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.The function returns the pointer to the Student pointer array.

bool destroyStudentList(Student ** studentList, int size);

The above 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.

Here are my functions :

Student ** createStudentList(char ** names, int size){

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

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

    return studentList;
}



bool destroyStudentList(Student ** studentList, int size) {
    if (studentList = NULL)
        return false;

    else {
        for (int i = 0; i < size; i++) {
            delete [] studentList[i]->name;
            studentList[i]->name = nullptr;
            delete studentList[i];
            studentList[i] = nullptr;
        }
        delete[] studentList;
        return true;
    }
}

It looks like function createStudentList works fine , but I get an error when trying to deallocate memory for delete [] studentList[i]->name; "Access violation reading location 0x00000000" . Why does it give me this error and how do I fix it ? Thank you

Upvotes: 0

Views: 158

Answers (2)

Anthony
Anthony

Reputation: 12397

You're almost there, but you have a few problems in your createStudentList function. Firstly, check the parentheses on this line:

studentList[i]->name = new char[strlen(names[i]+1)];

It doesn't quite do what you want.

Next, think about what this line is really doing,

studentList[i]->name = names[i];

Are you trying to make a copy of the string (which you must be, seeing as you're allocating memory for it)? If so, have another think about this line.

Upvotes: 1

Beta
Beta

Reputation: 99094

In createStudentList:

...
studentList[i]->name = new char[strlen(names[i]+1)];
studentList[i]->name = names[i];
...

Ouch! You allocate memory, then abandon it and set the name pointer to point to something that belongs to the argument names. You shouldn't expect that thing to still exist later on when you need it, and judging by your error message it's already passed out of scope or been deleted.

Upvotes: 2

Related Questions