I'm new to Gtkmm and trying to load a txt-file into a Text-Buffer. When I start my program I get a output like this: Output
My code for filling the Text-Buffers looks like this:
void ExampleGui::fill_buffers()
{
FILE *fp = fopen("/home/User/Documents/Gui/test1.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
char *line = NULL;
size_t len = 0;
char *output = NULL;
while ((getline(&line, &len, fp)) != -1) {
output = line;
}
fclose(fp);
if (line)
free(line);
m_refTextBuffer1 = Gtk::TextBuffer::create();
m_refTextBuffer1->set_text("Welcome!\nClick the button Show Text to start.");
m_refTextBuffer2 = Gtk::TextBuffer::create();
m_refTextBuffer2->set_text(Glib::convert_with_fallback(output, "UTF-8", "ISO-8859-1"));
}
How can I fix that wrong output and why do I get it?
The main problem here is the assignment output = line
followed by free(line)
.
Because output
points to the same memory as line
that means output
becomes invalid.
Either don't free the memory until you're done with the string, or duplicate the string in line
(which the assignment doesn't do).