Skip to content

Commit

Permalink
fix memory leak from rtmidi_get_port_name
Browse files Browse the repository at this point in the history
  • Loading branch information
torkeldanielsson committed Oct 14, 2020
1 parent 84d130b commit f922c14
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
20 changes: 15 additions & 5 deletions rtmidi_c.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -132,17 +132,27 @@ unsigned int rtmidi_get_port_count (RtMidiPtr device)
}
}

const char* rtmidi_get_port_name (RtMidiPtr device, unsigned int portNumber)
int rtmidi_get_port_name (RtMidiPtr device, unsigned int portNumber, char * bufOut, int * bufLen)
{
try {
std::string name = ((RtMidi*) device->ptr)->getPortName (portNumber);
return strdup (name.c_str ());
if (bufOut == nullptr && bufLen == nullptr) {
return -1;
}

std::string name;
try {
name = ((RtMidi*) device->ptr)->getPortName (portNumber);
} catch (const RtMidiError & err) {
device->ok = false;
device->msg = err.what ();
return "";
return -1;
}

if (bufOut == nullptr) {
*bufLen = static_cast<int>(name.size());
return 0;
}

return snprintf(bufOut, static_cast<size_t>(*bufLen), "%s", name.c_str());
}

/* RtMidiIn API */
Expand Down
8 changes: 6 additions & 2 deletions rtmidi_c.h
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,14 @@ RTMIDIAPI void rtmidi_close_port (RtMidiPtr device);
*/
RTMIDIAPI unsigned int rtmidi_get_port_count (RtMidiPtr device);

/*! \brief Return a string identifier for the specified MIDI input port number.
/*! \brief Access a string identifier for the specified MIDI input port number.
*
* To prevent memory leaks a char buffer must be passed to this function.
* NULL can be passed as bufOut parameter, and that will write the required buffer length in the bufLen.
*
* See RtMidi::getPortName().
*/
RTMIDIAPI const char* rtmidi_get_port_name (RtMidiPtr device, unsigned int portNumber);
RTMIDIAPI int rtmidi_get_port_name (RtMidiPtr device, unsigned int portNumber, char * bufOut, int * bufLen);

/* RtMidiIn API */

Expand Down

0 comments on commit f922c14

Please sign in to comment.