我有一个关于分配和释放内存的问题。
我想在循环中读取一个char缓冲区并将浮点值保存到一个向量中。我通过读取 fstream 来获取缓冲区。
但是我的方法在最后删除缓冲区时总是崩溃。
我在循环期间更改缓冲区是否有问题?有人知道如何解决这个问题吗?
我感谢每一个提示!
char* buffer1 = new char[size]; // the size is given
char* buffer2 = NULL;
fileStream.read(buffer1,size);
while(true)
{
// read double from buffer
// and get pointer to the new buffer -> buffer2
double tempDouble = strtod(buffer1, &buffer2);
// If nothing has been read (buffer stays the same) -> break
if (buffer1 == buffer2)
break;
else // change the buffer to read the next double during the next interation step
buffer1= buffer2;
// collect the doubles
collectedDoubles.push_back(tempDouble);
// if all numbers are read -> break
if (++doubleCount == numDoubles) // termination condition
break;
}
// delete the allocated buffer
delete[] buffer1;
// do I have th delete the 2nd buffer too?
// delete[] buffer2;