Description: fix segfault with freed lexicals
 If lexicals are freed, their memory becomes NULL, but
 PadWalker still tries to make a reference to it, causing
 a segmentation fault.
Origin: other
Bug: https://rt.cpan.org/Ticket/Display.html?id=55242
Author: Paul Driver <frodwith@gmail.com>
Reviewed-by: Jonathan Yu <jawnsy@cpan.org>
 gregor herrmann <gregoa@debian.org>
Last-Update: 2020-09-29

--- a/PadWalker.xs
+++ b/PadWalker.xs
@@ -261,10 +261,6 @@ pads_into_hash(pTHX_ PADNAMELIST* pad_na
               if (is_our) {
                 val_sv = fetch_from_stash(aTHX_ PadnameOURSTASH(name_sv),
                                           name_str, name_len);
-                if (!val_sv) {
-                    debug_print(("Value of our variable is undefined\n"));
-                    val_sv = &PL_sv_undef;
-                }
               }
               else
               {
@@ -273,6 +269,12 @@ pads_into_hash(pTHX_ PADNAMELIST* pad_na
                 if (!val_sv) val_sv = &PL_sv_undef;
               }
 
+              if (!val_sv) {
+                debug_print(("Value of %s variable is undefined\n",
+                  is_our ? "our" : "my"));
+                val_sv = &PL_sv_undef;
+              }
+
               hv_store((is_our ? our_hash : my_hash), name_str, PadnameUTF8(name_sv) ? -name_len : name_len,
                        (val_sv ? newRV_inc(val_sv) : &PL_sv_undef), 0);
             }
--- /dev/null
+++ b/t/dead_my.t
@@ -0,0 +1,11 @@
+use PadWalker qw(peek_my);
+
+print "1..1\n";
+
+my $outer = 42;
+sub {
+    my $inner = $outer;
+    sub { peek_my 0 }
+}->()->();
+
+print "ok 1\n";
