Cgo compiled c-shared binary string returned as strange encoding from C++ compiled with Ubuntu

I have a small amount of go code that I compile using cgo as a c-shared binary. This code is then later used in a C++ file that is compiled using gcc with Ubuntu.

Now when I use this same code but compile on M1 Mac everything is fine and the function’s returned string in C++ looks normal. However when I compile it in Ubuntu, again same code, the functions run without error but the function’s returned string is this strange garbled encoding. It looks like this but it differs on each run. I don’t think its encryption because the return string inside of the C code is normal.


// C

func GetOsStore(serviceName *C.char, keyName *C.char) *C.char {
	fmt.Println("GetOsStore start")
	backendType, err := getBackendType()
	if err != nil {
		panic("Getting backend type has failed! " + err.Error())
	fmt.Println("GetOsStore.BackendType", backendType)

	ring, openErr := keyring.Open(keyring.Config{
		AllowedBackends: []keyring.BackendType{backendType},
		ServiceName:     C.GoString(serviceName),
	if openErr != nil {
		fmt.Println("GetOsStore open keyring error", openErr)
	} else {
		fmt.Println("GetOsStore opened keyring")

	i, getErr := ring.Get((C.GoString(keyName)))
	dataStr := string(i.Data[:])
	returnStr := (*C.char)(C.CString(dataStr)) // returnStr prints without issue
	if getErr != nil {
		fmt.Println("GetOsStore get keyring error", getErr)
	} else {
		fmt.Println("GetOsStore got keyring")
	fmt.Println("GetOsStore end")
	return returnStr

// C++

Napi::String getOsStore(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  std::string serviceNameArg = info[0].As<Napi::String>().ToString();
  char *serviceName = new char[serviceNameArg.length() + 1];
  strcpy(serviceName, serviceNameArg.c_str());

  std::string keyNameArg = info[1].As<Napi::String>().ToString();
  char *keyName = new char[keyNameArg.length() + 1];
  strcpy(keyName, keyNameArg.c_str());

  Napi::String result = Napi::String::New(env, GetOsStore(serviceName, keyName));
  std::string resultStr = result.ToString();
  cout << "getOsStore from c++ string: " << resultStr; // both these cout produce the encoded text
  char *resultCStr = new char[resultStr.length() + 1];
  strcpy(resultCStr, resultStr.c_str());
  cout << "getOsStore from c string: " << resultCStr; 

  delete [] serviceName;
  delete [] keyName;
  return result;