Question

Firstly, I will show you my code.

std::ifstream file("accounts/22816.txt");
if(file){
   char *str[50];
   int count=0;
   str[0] = new char[50];
   while(file.getline(str[count], 50)){
      count++;
      str[count] = new char[50];
   }
   for(int i=0;i<count;i++){
      std::cout << str[i] << std::endl;
   }
   delete[] str;  // Here is the problem
}

The behavior of the previous code is:

  • Read the content of text file line by line.
  • Save each line in item of the 2D array.
  • Print the items of the 2D array.
  • Finally, delete the array from memory << and this reason of the problem.

When test my application always give me runtime error message _block_type_is_valid(phead- nblockuse).

I know the problem because this delete[] str;

Was it helpful?

Solution

str is an array of pointers, each of those pointers pointing to a dynamically allocated array.

You need to loop over it and call delete [] on each element.

for(int i=0; i < count; ++i){
  delete [] str[i];
}

Note: I have already provided OP with an example using std::vector, std::string and std::getline.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top