From 7e7d0f07b4a1c91a56c95af56ac14e2b535bb3c1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?S=C3=A9bastien=20Blin?=
 <sebastien.blin@savoirfairelinux.com>
Date: Wed, 12 Dec 2018 15:21:01 -0500
Subject: [PATCH] avmodel: avoid bad_alloc

Change-Id: Idcbd748900708f8e1de4de5196f272ab0b73f887
Reviewed-by: Kateryna Kostiuk<kateryna.kostiuk@savoirfairelinux.com>
---
 src/avmodel.cpp | 33 ++++++++++++++++++++++++++++-----
 1 file changed, 28 insertions(+), 5 deletions(-)

diff --git a/src/avmodel.cpp b/src/avmodel.cpp
index 100e267e..417bdfb4 100644
--- a/src/avmodel.cpp
+++ b/src/avmodel.cpp
@@ -644,15 +644,38 @@ std::string
 AVModelPimpl::getDevice(int type) const
 {
     if (type < 0 || type > 2) return {};  // No device
-    auto outputDevices = linked_.getAudioOutputDevices();
+    std::string result = "";
+    std::vector<std::string> devices;
+    switch (type) {
+        case 0: // INPUT
+            devices = linked_.getAudioInputDevices();
+            break;
+        case 1: // OUTPUT
+        case 2: // RINGTONE
+            devices = linked_.getAudioOutputDevices();
+            break;
+        default:
+            break;
+    }
     QStringList currentDevicesIdx = ConfigurationManager::instance()
         .getCurrentAudioDevicesIndex();
-    if (currentDevicesIdx.size() < 3
-    || outputDevices.size() != static_cast<size_t>(currentDevicesIdx.size())) {
-        // Should not happen, but cannot retrieve current ringtone device
+    try {
+        if (currentDevicesIdx.size() < 3
+        || devices.size() != static_cast<size_t>(currentDevicesIdx.size())) {
+            // Should not happen, but cannot retrieve current ringtone device
+            return "";
+        }
+        auto deviceIdx = currentDevicesIdx[type].toUInt();
+        if (deviceIdx >= devices.size()) {
+            // Incorrect device index
+            result = devices[0];
+        }
+        result = devices[deviceIdx];
+    } catch (std::bad_alloc& ba) {
+        qWarning() << "bad_alloc caught: " << ba.what();
         return "";
     }
-    return outputDevices[currentDevicesIdx[type].toUInt()];
+    return result;
 }
 
 void
-- 
GitLab