分段错误打开文件 c++

Segmentation fault opening a file c++

本文关键字:文件 c++ 错误 分段      更新时间:2023-10-16

我正在尝试设置一个简单的日志记录系统。

这是我的日志文件

#include <stdlib.h>
#include <string>
#include <fstream>
using namespace std;
class Log{
private:
    const static string ERROR;
    const static string WARNING; 
    const static string NOTICE;
    const static string DEBUG;
    const static string DEFAULT_FILENAME;
    static string filename;
    static ofstream* file;
public:
    Log();
    Log(string filename);
    ~Log();
    void init(string filename);
    static void log(string level, string msg);
    static void error(string msg);
    static void warning(string msg);
    static void notice(string msg);
    static void debug(string msg);
    static Log* getInstance();
};

以及日志中的实际代码.cpp

#include <stdlib.h>
#include <string>
#include "Log.h"
#include <fstream>
#include <iostream>
const string Log::ERROR = "ERROR";
const string Log::WARNING = "WARNING";
const string Log::NOTICE = "NOTICE";
const string Log::DEBUG = "DEBUG";
const string Log::DEFAULT_FILENAME = "log.txt";
string Log::filename;
ofstream* Log::file;
Log::Log(){
    this->init(DEFAULT_FILENAME);
}       
Log::Log(string filename){
    this->init(filename);
}       
Log::~Log(){ 
    this->file->close();
}       
void Log::init(string filename){
    Log::filename = filename; 
    cout << Log::file << " foo " << Log::filename.c_str() << endl;
    Log::file->open(filename.c_str(), ios::out | ios::app);
    cout << "bar" << endl;
    if(!Log::file->is_open()){
            throw 10;
    }
}
void Log::log(string level, string msg){
    if(Log::file == NULL)
            Log();
    cout << level << " : " << msg << endl;
    *Log::file << level << " : " << msg << endl;
}
void Log::error(string msg){
    log(ERROR, msg);
}
void Log::warning(string msg){
    log(WARNING, msg);
}
void Log::notice(string msg){
    log(NOTICE, msg);
}
void Log::debug(string msg){
    log(DEBUG, msg);
}

我的主要内容只包含:

Log::debug("Starting the server");

我编译:

g++  -Wall -std=c++11  -c -o main.o main.cpp
g++  -Wall -std=c++11  -c -o Log.o Log.cpp
g++ -lfcgi++ -lfcgi main.o Log.o -o main

当我执行时,我得到:

0 foo log.txt
make: *** [exec] Segmentation fault

打开文件的代码段错误。不知何故,这不是正确的问题,因为这段代码:

ofstream myfile;
myfile.open ("log.txt");
myfile << "Writing this to a file.n";
myfile.close();

效果很好。

你知道为什么我得到这个分段错误错误吗?

谢谢 !

我认为问题是你从来没有正确地创建Log::file。任何指针都必须使用 new 或某个等效的分配器进行初始化。您正在未初始化的指针上调用方法,并且代码在那里崩溃。

较小的示例起作用的原因是,您是在堆栈上分配的,而不是指向堆对象的指针。无论如何,这是最终解决这个问题的最好方法。使用堆分配的对象可能会变得非常混乱,除非您非常小心地管理所有权。

这是一种非常奇怪的使用流的方式,其中您有一个全局static实例,但您也有一个类。您可能应该将ofstream实例移动到对象中。

作为样式问题,没有必要在每个方法调用或属性引用之前放置this->,这是隐含的。只有在名称冲突的情况下才需要这样做。

以下是一些想法:

class Log {
private:
    string filename;
    ofstream file;
}
void Log::init(string filename_) {
    filename = filename_; 
    cout << file << " foo " << filename << ends;
    file.open(filename.c_str(), ios::out | ios::app);
    cout << "bar" << std::endl;
    if(!file.is_open()){
        throw 10;
    }
}