2020 New Year Coding Puzzler — The Curse of the Pointer

My coding started with C and I thus know pointers inside out. But do you? I will give you a bit of code, and there is a pointer problem…

2020 New Year Coding Puzzler — The Curse of the Pointer

My coding started with C and I thus know pointers inside out. But do you? I will give you a bit of code, and there is a pointer problem with it. Can you determine the bug?

The one thing I learn about pointers when I taught C, was that everything was fine, until we hit pointers and passing parameters with them, and most of the students struggled to get the concepts of them. The great thing about Golang is that we can use pointers, but also have the integration of GitHub code. If we have a program of msm.go, we compile it with:

$ go build msm.go

Here is the code in Golang, and which uses pointers for the creation of Big Integers, and which calculates x to the power of y:

package main
import "fmt"
import "strconv"
import "os"
import "math/big"
func exp_func(x, y *big.Int) *big.Int {
exp := strconv.FormatInt(y.Int64(), 2)
var value = new(big.Int)
value = x
fmt.Printf("Exp: %s \n", exp)
for i := 1; i < len(exp); i++ {
value.Mul(value,value)
  fmt.Printf("%d %d (square)\n", i,value)
if(exp[i]=='1') {
value.Mul(x,value)
fmt.Printf("%d %d (multiply) x=%s\n", i,value,x)
}
}
return value
}
func main() {
argCount := len(os.Args[1:])
x:="5"
y:="12"
 if (argCount>0) { x= os.Args[1]}
if (argCount>1) { y=os.Args[2]}
 xval,_ := new(big.Int).SetString(x,10)
yval,_ := new(big.Int).SetString(y,10)
 fmt.Printf("%d^%d is %s",xval,yval,exp_func(xval,yval))
}

If you know how to read C code, it shouldn’t be too difficult to read Golang code. When we run this program for 5¹² we get:

$ msn 5 12
Exp: 1100
1 25 (square)
1 625 (multiply) x=625
2 390625 (square)
3 152587890625 (square)
152587890625^12 is 152587890625

The program compiles, with no errors or warnings, but it gives us the wrong result. By changing one line of code (with just the addition of one character), we get the correct output of:

$ msn 5 12
Exp: 1100
1 25 (square)
1 125 (multiply) x=5
2 15625 (square)
3 244140625 (square)
5^12 is 244140625

Can you find the bug, and explain why the first program did not work?