关闭导致C++中linux下出现分段错误和“glibc检测到”的文本文件

close for text file causing segmentation fault and `glibc detected` under linux in C++

本文关键字:检测 glibc 文件 文本 错误 分段 C++ linux      更新时间:2023-10-16

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

#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下运行您的程序,或者通过调查核心转储(确保它启用了-AAIR-ulimit-c unlimited)。

问题是我们在检查所有线程是否完成时遇到了问题。我们已经把它修好了,现在一切正常。这个问题可能是因为其他线程试图访问关闭的文件,有时还试图访问终止的实体。