Weird usage of runtime.KeepAlive(x any)

In x/sys package, there are a few uses of rutime.KeepAlive(x any) function.

One of these is in windows/setupapi_windows.go SetupDiGetDeviceProperty():

func SetupDiGetDeviceProperty(deviceInfoSet DevInfo, deviceInfoData *DevInfoData, propertyKey *DEVPROPKEY) (value interface{}, err error) {
	reqSize := uint32(256)
	for {
		var dataType DEVPROPTYPE
		buf := make([]byte, reqSize)
		err = setupDiGetDeviceProperty(deviceInfoSet, deviceInfoData, propertyKey, &dataType, &buf[0], uint32(len(buf)), &reqSize, 0)
		if err == ERROR_INSUFFICIENT_BUFFER {
			continue
		}
		if err != nil {
			return
		}
		switch dataType {
		case DEVPROP_TYPE_STRING:
			ret := UTF16ToString(bufToUTF16(buf))
			runtime.KeepAlive(buf)
			return ret, nil
		}
		return nil, errors.New("unimplemented property type")
	}
}

What is runtime.KeepAlive(buf) trying to achieve here, and can it not cause a memory leak?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.