pass_scope_dealloc.mx raw

   1  package main
   2  
   3  type Pair struct {
   4  	A int32
   5  	B int32
   6  }
   7  
   8  // allocAndReturn heap-allocates a Pair and returns it (escape path).
   9  // The dealloc sweep at function return must NOT free this allocation.
  10  func allocAndReturn(a int32, b int32) (result *Pair) {
  11  	result = &Pair{A: a, B: b}
  12  	return result
  13  }
  14  
  15  // allocAndDiscard heap-allocates a Pair but does not return it.
  16  // The dealloc sweep at function return frees this allocation.
  17  // Calling this repeatedly exercises free-list reuse.
  18  func allocAndDiscard(a int32, b int32) (sum int32) {
  19  	p := &Pair{A: a, B: b}
  20  	sum = p.A + p.B
  21  	return sum
  22  }
  23  
  24  func main() {
  25  	// Test escape path: returned pointers survive dealloc.
  26  	p1 := allocAndReturn(10, 20)
  27  	p2 := allocAndReturn(30, 40)
  28  	if p1.A == 10 && p1.B == 20 && p2.A == 30 && p2.B == 40 {
  29  		println("PASS: escaped allocs survive dealloc")
  30  	} else {
  31  		println("FAIL: escaped allocs corrupted")
  32  	}
  33  
  34  	// Test free path: discarded allocs freed, free-list reuse works.
  35  	ok := true
  36  	for i := int32(0); i < 100; i++ {
  37  		s := allocAndDiscard(i, i+1)
  38  		if s != i+i+1 {
  39  			ok = false
  40  		}
  41  	}
  42  	if ok {
  43  		println("PASS: 100 alloc+free cycles without crash")
  44  	} else {
  45  		println("FAIL: alloc+free cycle produced wrong value")
  46  	}
  47  }
  48