I tried to construct a ifstream
object in side a static class method GetFile() but I got a segmentation fault. I was able to recreate the error by allocating any memory on the heap. Any allocation of memory on the heap in this method causes it to throw a segmentation fault error. Why does this happen and how can I fix it?
Header definition:
static ErrorOr<std::unique_ptr<MemoryBuffer>>
GetFile(const char *const Filename);
Body:
ErrorOr<std::unique_ptr<MemoryBuffer>>
MemoryBuffer::GetFile(const char *const Filename) {
std::ifstream Input(Filename, std::ifstream::ate | std::ifstream::in | std::ifstream::binary);
int64_t S = Input.tellg();
Input.seekg(0, Input.beg);
if (Input.fail()) {
std::cerr << "Error: " << std::strerror(errno) << std::endl;
}
char *Mem = static_cast<char *>(operator new(S + 1));
Mem[S] = '\0';
std::unique_ptr<MemoryBuffer> MemBuf(new MemoryBuffer(&Mem[0], &Mem[S + 1]));
return ErrorOr<std::unique_ptr<MemoryBuffer>>(std::move(MemBuf));
}
And I call the method by MemoryBuffer::GetFile("Testfile.txt");
Aucun commentaire:
Enregistrer un commentaire