C++ – Allocate and Delete memory for pointers in a struct C++


Given the following struct declaration:

struct Student


   char *     name;
   int  *     test;
   float      gpa;


int main() {

Student *newObject = new Student;

newObject->name = new char[10];
newObject->test = new int;

return 0;

My question is how do I destroy the created dynamic variables ?
I tried delete newObject->name; and delete newObject->test;but it doesn't seem to work because it shows me the same addresses as before delete . Is it just enought to delete the object by using delete newObject; newObject = nullptr;?

Best Solution

It would have to be

delete[] newObject->name;
delete newObject->test;
delete newObject;

because name was allocated with new[] while the other two were allocated with new. Neither delete nor delete[] changes the pointer value, though, it just invalidates what the pointer used to point to.

However, doing it this way is rather terribad. In the case of the object itself and the int, there is no reason to use dynamic allocation at all, and for name there's a class in the standard library called std::string that does the memory management for you. It would be best to replace the code with

#include <string>

struct Student {
  std::string name;
  int         test;
  float       gpa;

int main() {
  Student newObject;

  // do stuff, for example
  newObject.name = "John Doe";
  newObject.test = 123;
  newObject.gpa  = 3.1415926;

  // no manual cleanup necessary; it happens automatically when
  // newObject goes out of scope.
  return 0;