QString conversion of MIDI meta message text needs fixing

• Feb 24, 2010 - 22:04
S4 - Minor

MIDI meta message text strings are not null-terminated. When converting these text strings into QString objects, this should be taken into account. For example in importmidi.cpp, in the function:
void MidiFile::processMeta(Score* cs, MidiTrack* track, Event* mm)

The track name is extracted with the code:

00695 case META_TRACK_NAME:
00696 if (staff) {
00697 QString txt((char*)data);
00698 track->setName(txt);
00699 }
00700 break;

However, extra garbage characters are present in the staff name in MuseScore because of no null character termination of the string in the MIDI data.

Line 697 (and similar places in the file) contains a conversion of a C string into a QString. However, the (char*)data string is not null terminated, so it is better to create a temporary string with a null on the end, or something to the similar effect:

if (staff) {
QString txt((char*)data);

Should be something like:

if (staff) {
char* tempdata = new char[mm->len()+1];
strncpy(tempdata, data, mm->len());
tempdata[mm->len()] = '\0';
QString txt((char*)tempdata);
delete [] tempdata;

Probably a better method, is to add the null character to the end of data when it is extracted from the meta message:
unsigned char* data = (unsigned char*)mm->data();
changes to:
unsigned char* data = new char[mm->len()+1];
strncpy(data, mm->data(), mm->len());
data[mm->len()] = '\0';
Then data contains a null termination, and other parts of the function will not have to be altered (you will have to figure out how to dispose of the temporary object in this case).

Alternatively, you could always append a null character after the official data length of an event data array so that the array would appear to be null-terminated, although the null character would not be part of the actual data length reported by the Event::len() function (sometimes meta messages are not text, so you would not want the null character to be visible in non-text meta messages).


I cannot reproduce this bug. Meta Event data is (and was) always terminated with a (not counted) zero in MuseScore. The observed trailing garbage in track names may have another reason. Maybe the bug is fixed with some changes in the handling of instrument names.