From 290354e3f6d8905981f1deab31086ccdfcd09c69 Mon Sep 17 00:00:00 2001
From: Roberto Fernandez Bautista <roberto.fer.bau@gmail.com>
Date: Sat, 5 Feb 2022 19:18:49 +0000
Subject: [PATCH] CADSTAR: Fix potential nullptr dereferencing bug Don't assume
 the footprint will have the pad index that the file references.

---
 .../cadstar/cadstar_pcb_archive_loader.cpp      | 17 ++++++++++++-----
 1 file changed, 12 insertions(+), 5 deletions(-)

diff --git a/pcbnew/plugins/cadstar/cadstar_pcb_archive_loader.cpp b/pcbnew/plugins/cadstar/cadstar_pcb_archive_loader.cpp
index f5d761fe4b..3b19332f36 100644
--- a/pcbnew/plugins/cadstar/cadstar_pcb_archive_loader.cpp
+++ b/pcbnew/plugins/cadstar/cadstar_pcb_archive_loader.cpp
@@ -1250,7 +1250,15 @@ PAD* CADSTAR_PCB_ARCHIVE_LOADER::getKiCadPad( const COMPONENT_PAD& aCadstarPad,
 PAD*& CADSTAR_PCB_ARCHIVE_LOADER::getPadReference( FOOTPRINT*   aFootprint,
                                                    const PAD_ID aCadstarPadID )
 {
-    return aFootprint->Pads().at( aCadstarPadID - (long long) 1 );
+    size_t index = aCadstarPadID - (long) 1;
+
+    if( !( index < aFootprint->Pads().size() ) )
+    {
+        THROW_IO_ERROR( _( "Unable to find pad index '%d' in footprint '%s'.", (long) aCadstarPadID,
+                           aFootprint->GetReference() ) );
+    }
+
+    return aFootprint->Pads().at( index );
 }
 
 
@@ -1703,12 +1711,11 @@ void CADSTAR_PCB_ARCHIVE_LOADER::loadComponents()
                     csPad.Side = padEx.Side;
 
                 // Find the pad in the footprint definition
-                PAD*     kiPad = getPadReference( footprint, padEx.ID );
+                PAD* kiPad = getPadReference( footprint, padEx.ID );
+
                 wxString padNumber = kiPad->GetNumber();
 
-                if( kiPad )
-                    delete kiPad;
-
+                delete kiPad;
                 kiPad = getKiCadPad( csPad, footprint );
                 kiPad->SetNumber( padNumber );