PDA

View Full Version : EXC_BAD_ACCESS error in redirecting ostream to QTextEdit to make a log window



owen_263
9th July 2008, 05:43
The class is provided like this,

class QDebugStream : public std::basic_streambuf<char>
{
public:
QDebugStream(std::ostream &stream, QTextEdit* text_edit) : m_stream(stream)
{
log_window = text_edit;
m_old_buf = stream.rdbuf();
stream.rdbuf(this);
}
~QDebugStream()
{
// output anything that is left
if (!m_string.empty())
log_window->append(m_string.c_str());

m_stream.rdbuf(m_old_buf);
}

protected:
virtual int_type overflow(int_type v)
{
if (v == '\n')
{
log_window->append(m_string.c_str());
m_string.erase(m_string.begin(), m_string.end());
}
else
m_string += v;

return v;
}

virtual std::streamsize xsputn(const char *p, std::streamsize n)
{
m_string.append(p, p + n);

std::string::size_type pos = 0;
while (pos != std::string::npos)
{
pos = m_string.find('\n');
if (pos != std::string::npos)
{
std::string tmp(m_string.begin(), m_string.begin() + pos);
log_window->append(tmp.c_str());
m_string.erase(m_string.begin(), m_string.begin() + pos + 1);
}
}

return n;
}

private:
std::ostream &m_stream;
std::streambuf *m_old_buf;
std::string m_string;
QTextEdit* log_window;
};

The Usage is like this:

[...]
QTexEdit* myTextEdit = new QTextEdit(this, "myTextEdit");
myTextEdit->setTextFormat(Qt::LogText);

QDebugStream qout(std::cout, myTextEdit);

std::cout << "Send this to the Text Edit!" << endl;
[...]

After the EXC_BAD_ACCESS error, GDB backtrace shows:

#0 0x013b8819 in QTextEdit::append ()
#1 0x000108e7 in QDebugStream::overflow (this=0xbffff390, v=10) at qDebugStream.h:76

frame 1 is at:
" log_window->append(m_string.c_str()); "

I guess the problem is from the header file. Anyone could help me? I will appreciate that.

jacek
9th July 2008, 21:52
What happens if you replace "QTextEdit* log_window" with "QPointer< QTextEdit > log_window" in line 56?

owen_263
11th July 2008, 03:20
I tried, but the bug remains~ The "qDebugStream.h" is from 2005's qt forum thread, old enough to introduce bugs for the Newer Qt framework... If we can update this header.

jacek
11th July 2008, 20:04
I tried, but the bug remains~
Did the backtrace change?

owen_263
15th July 2008, 03:38
Yes, the backtrace doesn't change at all~
Sorry for delay for the reply. Sometimes i can't write on the forum, it's really weird.

jacek
17th July 2008, 13:12
What happens if you add "if( ! log_window.isNull() )" before every log_window->append(...) (and of course keep the QPointer<> in the class definition)?

Do you use threads?