gpt4 book ai didi

c++ - 当 ofstream 超出范围时偶尔出现 SEG FAULT

转载 作者:太空宇宙 更新时间:2023-11-04 12:05:16 25 4
gpt4 key购买 nike

当 std::ofstream 超出范围时,我很少遇到段错误问题。我的 Logger.h 中有以下结构:

        struct LogRequest
{
std::string line;
std::string prefix;
};

struct FileInfo
{
std::string name;
std::ofstream ofs;
int lines;
std::string ToString()
{
return (name + " exists");
};

在 Logger.cpp 中,我有以下函数:

void Logger::Log(const std::string line, std::string prefix)
{
pthread_mutex_lock(&mutex);
if (file_map.find(prefix) == file_map.end())
{
OpenLogFile(prefix);
}

LogRequest* request = new LogRequest;
request->line = line;
request->prefix = prefix;
message_queue.push_back(request);
pthread_mutex_unlock(&mutex);
}

void Logger::OpenLogFile(const std::string& prefix)
{
//get timestamp to use
char timestamp[15];
time_t now;
time(&now);
struct tm* current = localtime(&now);
sprintf(timestamp, "%02u%02u%04u_%02u%02u%02u", (current->tm_mon+1),
current->tm_mday,(1900 + current->tm_year), current->tm_hour,
current->tm_min, current->tm_sec);

FileInfo* info = new FileInfo;
info->name = "logs/" + prefix + ".log_" + timestamp;
info->ofs.open(info->name.c_str(), std::ios::out);
info->lines = 0;

file_map[prefix] = info;
}

void Logger::CloseLogFile(const std::string& prefix)
{
delete file_map[prefix];
}

在 Logger.cpp 的线程中,我有...

void Logger::WriteToFile()
{
std::map<std::string, FileInfo* >::iterator it;

while(run)
{
char timestamp[16];
time_t now;
time(&now);
struct tm* current = localtime(&now);
sprintf(timestamp, "%02u%02u%04u|%02u%02u%02u|", (current->tm_mon+1),
current->tm_mday,(1900 + current->tm_year), current->tm_hour,
current->tm_min, current->tm_sec);

pthread_mutex_lock(&mutex);
for(it=file_map.begin(); it != file_map.end(); ++it)
{
if(it->second->lines > MAX_LINES)
{
CloseLogFile(it->first);
OpenLogFile(it->first);
}
else
{
int written = 0;

while(!message_queue.empty() && written < MESSAGES_PER_WRITE)
{
LogRequest* request = message_queue.front();
message_queue.pop_front();

std::string line(timestamp, 16);
line.append(request->line);

FileInfo* info = file_map[request->prefix];
info->ofs << line << std::endl;
info->lines++;
written++;
delete request;
}
}
}
pthread_mutex_unlock(&mutex);

usleep(1000);
}
}

我遇到的问题是,当我尝试 CloseLogFile 时,有时会在 FileInfo 中的 std::ofstream ofs 的析构函数中抛出段错误。 .它工作了很多次。甚至在 SEG 错误发生之前(通过各种 cout 语句)我已经确认 std::ofstream 是好的,没有失败,没有达到 eof,而且还不错。我还确认 file_map[prefix] 存在,并且通过输出 FileInfo 的 ToString() 也存在。这些都是在 CloseLogFile 中删除之前检查的。

我的问题是关于 SEG FAULT 的原因。

此外,当行在 WriteToFile() 中输出到 ofstream 时,如果我删除 LogRequest 对象是否可以?如,info->ofs << line << std::endl; 中究竟发生了什么?行?

最佳答案

看起来您的 sprintf(timestamp...) 调用被一个字符(null)覆盖,这将导致未定义的行为。尽管这可能是也可能不是您的主要问题,因为它在线程堆栈上并且您的文件在堆上......

关于c++ - 当 ofstream 超出范围时偶尔出现 SEG FAULT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12427673/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com