系统相关
首页 > 系统相关> > 关闭导致分段错误的文本文件,并在Linux下在Linux下检测到“ glibc”

关闭导致分段错误的文本文件,并在Linux下在Linux下检测到“ glibc”

作者:互联网

我有一个日志类,该类包含一个定义为:流日志文件的流和一个互斥体,以确保每次只有一个线程写入文件(程序是多线程的).
该类定义为:

#define LOG_NAME "log.txt"

using namespace std;

class Log
{
private:
    pthread_mutex_t mutex_write;
    ofstream logfile;

public:
    Log();
    ~Log();
    void Write (string txt);
};

构造函数是:

Log::Log()
{
    pthread_mutex_init (&mutex_write,NULL);
    pthread_mutex_lock (&mutex_write);
    logfile.open(LOG_NAME, ios::out | ios::trunc);
    logfile << "Created log file named " << LOG_NAME << endl;
    pthread_mutex_unlock (&mutex_write);
}

析构函数为:

Log::~Log()
{
    logfile << "Closing log file" << endl;
    pthread_mutex_lock (&mutex_write);
    logfile.close();
    pthread_mutex_unlock (&mutex_write);
    pthread_mutex_destroy (&mutex_write);
}

和:

void Log::Write (string txt)
{
    pthread_mutex_lock (&mutex_write);
    logfile << txt << endl;
    pthread_mutex_unlock (&mutex_write);
}

在某些时候,调用析构函数时,它无法执行logfile.close();行.因为它说它遇到了分段错误,或者显示了消息:

*** glibc detected *** corrupted double-linked list: 0x0000000000513eb0 ***
Abort

这种情况并非一直发生,它似乎是随机发生的,大约是10%的时间.该程序是多线程的(在Linux下).

编辑:
用法示例:(其中log是指向Log类的对象的指针)

stringstream str;
str.str("");
str << "Ant " << i << " was created at place: (" << x << "," << y << ")";
log->Write (str.str());

或者,如果字符串仅包含已知文本

log->Write ("Created board entity");

解决方法:

不确定100%,但是它可能与代码中任何地方的内存损坏有关.
要更深入地研究此问题,请尝试在Valgrind下运行程序或通过调查核心转储(确保已启用-AFAIR ulimit -c unlimited).

标签:text,glibc,linux,c-4,segmentation-fault
来源: https://codeday.me/bug/20191208/2090829.html