2

I have the code below which contains a dynamic array of strings. I'm having problems deallocating each individual string that is generated. I assumed I could just include a new for loop which deallocated them but that didn't work. How should I be doing this?

//A dynamically allocated array of char pointers
int numOfStrings = 10, numOfChars = 32;
char** data = new char*[numOfStrings];

//Generate each each individual string
for(int i = 0; i <numOfStrings; i++)
    data[i] = new char[numOfChars];

//moves the elements 1-5 in the array to the right by one
int index = 1, boundary = 5, sizeToMove = (boundary - index) * sizeof(numOfChars);
memmove(&data[index + 1],&data[index],sizeToMove);

for(int i=0;i < numOfStrings; i++)
delete [] data[i];   //this line is causing an exception on its first call (I've also tried delete data[i].

delete[] data;
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 3
    It would be a lot easier to use the tools of C++. `std::vector data(numOfStrings);` – Martin York Apr 01 '13 at 20:57
  • you are moving memory of your array itself, you don't want to take the addresses of data, but the pointer pointed by data. also check your sizeof(numOfChars) because it is equivalent to sizeof(int) are you sure you want that ? – v.oddou Apr 04 '13 at 01:50

1 Answers1

2

Other than what its name suggests, memmove does not actually "move" the bytes. It copies them (but, in contrast to memcpy, it can do this correctly even when the source and destination areas overlap).

Therefore, after "moving" the contents from the source area to the destination area, those elements that were located in non-overlapping parts are still unchanged. In particular, data[index] is unchanged, and therefore identical with the contents of data[index+1] after your memmove().

Hence, any attempt to delete [] data[index+1] will try to free the same memory that is freed when doing delete [] data[index]. That's illegal.

To solve this, you need to set data[index] (or generally speaking, any non-overlapping part of the source area) to 0 (or nullptr) after the move, or take other measures to ensure that it is not deleted.

The simplest direct fix given your code is to insert

data[index] = 0;

before the delete-loop.

jogojapan
  • 68,383
  • 11
  • 101
  • 131