Index: generic/tclCompile.c
===================================================================
RCS file: /cvsroot/tcl/tcl/generic/tclCompile.c,v
retrieving revision 1.188
diff -u -r1.188 tclCompile.c
--- generic/tclCompile.c	27 Sep 2010 19:42:38 -0000	1.188
+++ generic/tclCompile.c	6 Oct 2010 18:21:43 -0000
@@ -1050,12 +1050,12 @@
 {
     register ByteCode *codePtr = objPtr->internalRep.ptrAndLongRep.ptr;
 
+    objPtr->typePtr = NULL;
+    objPtr->internalRep.otherValuePtr = NULL;
     codePtr->refCount--;
     if (codePtr->refCount <= 0) {
 	TclCleanupByteCode(codePtr);
     }
-    objPtr->typePtr = NULL;
-    objPtr->internalRep.otherValuePtr = NULL;
 }
 
 /*
Index: tests/subst.test
===================================================================
RCS file: /cvsroot/tcl/tcl/tests/subst.test,v
retrieving revision 1.20
diff -u -r1.20 subst.test
--- tests/subst.test	8 Apr 2010 13:26:25 -0000	1.20
+++ tests/subst.test	6 Oct 2010 18:21:43 -0000
@@ -271,6 +271,30 @@
     set y unset
     list [eval [list subst {[set x 1;continue;incr x][set y $x]}]] $x $y
 } {1 1 1}
+
+test subst-13.1 {Bug 3081065} -setup {
+    set script [makeFile {
+	proc demo {string} {
+	    subst $string
+	}
+	demo name2
+    } subst13.tcl]
+} -body {
+    interp create slave
+    slave eval [list source $script]
+    interp delete slave
+    interp create slave
+    slave eval {
+	set count 400
+	while {[incr count -1]} {
+	    lappend bloat [expr {rand()}]
+	}
+    }
+    slave eval [list source $script]
+    interp delete slave
+} -cleanup {
+    removeFile subst13.tcl
+}
 
 # cleanup
 ::tcltest::cleanupTests
