현재 메모리 사용량이 적은 응용 프로그램을 최적화하여 메모리를 덜 차지합니다. 다음 코드에서 수행하려는 작업은 더 이상 필요없는 파일 스트림 객체를 정확하게 해제하기 위해 파일 스트림 객체 ifstream
및 ofstream
을 동적으로 할당하는 것입니다. 이 코드는 ofstream
의 할당/할당 해제를 위해 완벽하게 기능하지만, ifstream
의 메모리 내용이 할당 해제 될 때 가능한 분할 오류로 인해 런타임에 충돌합니다. 사용자가 기능을 저장 불러 일으키는 경우 위의 코드는 이진 파일에 객체를 저장예기치 않은 런타임 오류 (세그먼트 화 오류)
#include <fstream>
using namespace std;
// Dummy class to emulate the issue at hand
class dummy {
private:
int randINT;
static bool isSeeded;
public:
dummy() { randINT=rand(); }
int getVal() { return randINT; }
};
bool dummy::isSeeded=false;
int main(int argc, const char* argv[]) {
// Binary file I/O starts here
dummy * obj;
ofstream * outputFile;
ifstream * inputFile;
outputFile=new ofstream("bFile.bin",ios::binary);
if (!(*outputFile).fail()) {
obj=new dummy;
cout << "Value to be stored: " << (*obj).getVal() << "\n";
(*outputFile).write((char *) obj, sizeof(*obj)); // Save object to file
(*outputFile).close();
delete obj;
// don't assign NULL to obj; obj MUST retain the address of the previous object it pointed to
} else {
cout << "Error in opening bFile.bin for writing data.\n";
exit(1);
}
delete outputFile; // This line throws no errors!
inputFile=new ifstream("bFile.bin",ios::binary);
if (!(*inputFile).fail()) {
(*inputFile).read((char *) obj,sizeof(dummy)); // Read the object of type 'dummy' from the binary file and allocate the object at the address pointed by 'obj' i.e. the address of the previously de-allocated object of type 'dummy'
cout << "Stored Value: " << (*obj).getVal() << "\n";
(*inputFile).close();
} else {
cout << "Error in opening bFile.bin for reading data.\n";
exit(1);
}
delete inputFile; // Runtime error is thrown here for no reason!
cout << "\n-----END OF PROGRAM-----\n";
}
: 다음은 원본 코드의 조각이다. 위의 코드에서 설명한 것처럼 inputFile
포인터의 할당 해제는 런타임 오류를 발생시킵니다.
clang (더 구체적으로 clang ++)을 사용하여 프로젝트를 컴파일하고 있습니다.
미리 감사드립니다.
질문을 [편집]하여 [mcve]를 제공해주십시오. –
Java 또는 C# 배경에서 왔습니까? 왜냐하면 C++에서는 객체의 인스턴스를 만들기 위해'new'를 사용할 필요가 없기 때문입니다. 그리고 포인터가 적어지고, 포인터를 잘못 사용하는 것이 충돌의 가장 일반적인 이유이기 때문에 포인터가 적을수록 좋습니다. –
'outputFile = new ofstream ("bFile.bin", ios :: binary);은 매우 나쁜 생각입니다. 의도적으로 [RAII] (https://en.wikipedia.org/wiki/)를이기려고합니까? Resource_acquisition_is_initialization)? – WhiZTiM