关闭导致C++中linux下出现分段错误和“glibc检测到”的文本文件
close for text file causing segmentation fault and `glibc detected` under linux in C++
我有一个日志类,该类包含一个定义为: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)。
问题是我们在检查所有线程是否完成时遇到了问题。我们已经把它修好了,现在一切正常。这个问题可能是因为其他线程试图访问关闭的文件,有时还试图访问终止的实体。
相关文章:
- 未知C++错误:致命错误:glibc检测到无效的stdio句柄
- 从检测到 glibc 正常退出 - malloc():内存损坏
- ***检测到的GLIBC *** MS2:free():无效指针:0xB7526FF4 ***
- glibc 检测到 *** free() 无效指针
- 错误: *** 检测到 glibc *** w5:双重释放或损坏(快速顶部):
- GLIBC检测到矩阵乘法中的误差
- *** glibc检测到*** free():无效的指针:
- glibc 检测到内存库拉
- 错误消息glibc检测到Malloc():内存损坏(快速)
- glibc 检测到双重释放或损坏
- c++提升线程glibc检测到无效指针
- 检测旧GLIBC版本的堆栈溢出
- C++glibc检测到损坏的双链表错误C++
- 有人能向我解释一下我的代码的哪一部分导致***检测到glibc***吗/a2:free():无效的下一个大小(快速)
- glibc 检测到双重释放或损坏
- glibc 检测到 free() 无效指针
- glibc 检测小箱链表已损坏
- glibc 检测到 free() 无效大小(快速)错误
- glibc 检测到 *** ./burcu.exe: free(): 无效的下一个大小 (快速): 0x00000000
- C++:glibc检测到损坏的双链表:0x08f8f148