Deallocating member pointer

Nick
#include <iostream>

using namespace std;


class myClass{

public:
    char * pointer;
    char * pointerToPointer;

myClass(){
  pointer = new char;
      char x = 'x';
      pointer = &x;

  pointerToPointer = new char[3];
      char y[3] = {'x', 'y', 'z'};
      pointerToPointer = y;
}
~myClass(){
  delete pointer;
  delete[] pointerToPointer;
}};

int main(){
myClass myclass;
return 0;
}

I am new to c++, so I apologize if this question has been beaten to death, but I couldn't seem to find an answer online.

I am trying to include two pointers in my class. One that points to a single letter, and the other that points to an array of chars. From what i understand every time the new keyword is included it should be accompanied by the delete keyword at some point in the code.

I have included a destructor that should deallocate the memory allocated to these pointers, but when it is called in the main function upon the program termination i am left with:

Error in `./a.out': munmap_chunk(): invalid pointer: 0x00007fffcabc5600 *** Aborted (core dumped)

Any advice / suggestions on what i should be googling would be greatly appreciated.

vsoftco

Below

  pointerToPointer = new char[3];
  char y[3] = {'x', 'y', 'z'};
  pointerToPointer = y;

you allocate memory to pointerToPointer (first line), then make pointerToPointer point to the beginning of the array y (third line). When you try to delete pointerToPointer, you effectively try to delete a pointer that points to a non-dynamic array. This causes the segfault, as the memory for y is automatically released by the runtime and you try to release it again in the destructor.

In any case, switching the pointer to point to some other memory location should be done with care, as it may create memory leaks if you forget to deallocate the initial allocated memory (the new char[3] in your case).

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related