Solved QString append vs insert inside loop
-
char buf[80]; QString str; QTextstream ts; volatile int pos=0;
Inside a loop, get 80 chars from ts into buf, test for the end condition, if not end, str.append(buf). I noticed strange chars getting into str. The doc on QString::append says append "preallocates extra space at the end of the string data so it can grow without reallocating the entire string each time." Do subsequent appends place the new data at the end of the preallocated extra space? That would explain the garbage every mod(80) of the final QString.
I changed str.append to str.insert(pos, buf) to get around this unexpected behavior. -
Please show us your code. The internal pre-allocation has for sure nothing to do with your problems.
-
Thank you for your reply. I re-designed the function with a different algorithm. Thank for the clarification. Append joins existing and new strings.
-
@psnarf if you append from a char[] array, that must be properly null-terminated. otherwise you get jndefined behavior.
Regards
-
Thank you, Aha. The FITS header consists of 80-char 'cards' probably from days of Hollerith punched cards. The header has no delimiters, a 200-card header is a 16,000 char string. Will go back and try null-terminated strings in a ListWidget, but now using QStringListModel with QListView. I'm sure the missing null termination produced the undefined behavior, with appended strings beginning half a dozen chars past the previous string. Appreciate your kind explanation!
-
@Psnarf
"nul terminated strings" emerged as a convention with the definition of the C programming languages in the 1970s. Your "Hollerith punched cards" emerged in the 1890s, as in 1890s not 1990s! :)I presume you cannot assume any nul-termination. That means you cannot treat the 80 characters via functions which take a C-style-terminated string. At a guess, to produce a
QString
try https://doc.qt.io/qt-5/qstring.html#fromLatin1 or https://doc.qt.io/qt-5/qstring.html#fromLocal8Bit, passing80
for the size parameter.