react-native-reanimated: Memory leak in `useSharedValue`

Description

The memory used by a useSharedValue is never released when the component is unmounted and is always held

Steps to reproduce

Create a flatlist component that renders some subcomponents, the subcomponents all useSharedValues. Swipe through the list and you’ll see that the amount of memory keeps on increasing and it’s never released. Running the hermes profiler and you’ll see that the useSharedValue comes up a lot with the number of allocations. I’ve attached a repo below where you can take a look, this seems to be similar to #5614. I can add more information if needed

I’ve also included a video, if you look at the memory usage, you’ll see it continuously increase and never go down

https://github.com/software-mansion/react-native-reanimated/assets/19998186/890b619f-4dd8-4b8f-9c3a-76c4e5119f3f

Snack or a link to a repository

https://github.com/Lapz/reanimated-shared-values-leak

Reanimated version

3.8.0

React Native version

0.73.5

Platforms

iOS

JavaScript runtime

Hermes

Workflow

Expo Go

Architecture

Paper (Old Architecture)

Build type

None

Device

iOS simulator

Device model

No response

Acknowledgements

Yes

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Comments: 17 (9 by maintainers)

Most upvoted comments

my knowledge on C: 0

I asked ChatGPT about the SingleInstanceChecker.h under Common/cpp/Tools to suggest some improvements and it gave me back this:

Click me
#pragma once

#ifndef NDEBUG

#include <cxxabi.h>

#include <atomic>
#include <iostream>
#include <string>

#ifdef ANDROID
#include <android/log.h>
#endif

namespace reanimated {

// This is a class that counts how many instances of a different class there
// are. It is meant only to be used with classes that should only have one
// instance.

template <class T>
class SingleInstanceChecker {
 public:
  SingleInstanceChecker();
  ~SingleInstanceChecker();

 private:
  void assertWithMessage(bool condition, std::string message) {
    if (!condition) {
#ifdef ANDROID
      __android_log_print(
          ANDROID_LOG_WARN, "Reanimated", "%s", message.c_str());
#else
      std::cerr << "[Reanimated] " << message << std::endl;
#endif

#ifdef IS_REANIMATED_EXAMPLE_APP
      assert(false);
#endif
    }
  }

  // A static field will exist separately for every class template.
  // This automatically initializes the inline variable.
  inline static std::atomic<int> instanceCount_{0};
};

template <class T>
SingleInstanceChecker<T>::SingleInstanceChecker() {
  int status = 0;
  char* demangled_name = __cxxabiv1::__cxa_demangle(typeid(T).name(), nullptr, nullptr, &status);

  std::string className =
      (status == 0 && demangled_name != nullptr) ? demangled_name : typeid(T).name();

  assertWithMessage(
      instanceCount_.load() <= 1,
      "[Reanimated] More than one instance of " + className +
          " present. This may indicate a memory leak due to a retain cycle.");

  instanceCount_.fetch_add(1);

  free(demangled_name);
}

template <class T>
SingleInstanceChecker<T>::~SingleInstanceChecker() {
  instanceCount_.fetch_sub(1);
}

} // namespace reanimated

#endif // NDEBUG

in patch format (v3.8.1):

diff --git a/node_modules/react-native-reanimated/Common/cpp/Tools/SingleInstanceChecker.h b/node_modules/react-native-reanimated/Common/cpp/Tools/SingleInstanceChecker.h
index 2a183e8..8fc21d6 100644
--- a/node_modules/react-native-reanimated/Common/cpp/Tools/SingleInstanceChecker.h
+++ b/node_modules/react-native-reanimated/Common/cpp/Tools/SingleInstanceChecker.h
@@ -41,29 +41,31 @@ class SingleInstanceChecker {
   }
 
   // A static field will exist separately for every class template.
-  // This has to be inline for automatic initialization.
-  inline static std::atomic<int> instanceCount_;
+  // This automatically initializes the inline variable.
+  inline static std::atomic<int> instanceCount_{0};
 };
 
 template <class T>
 SingleInstanceChecker<T>::SingleInstanceChecker() {
   int status = 0;
+  char* demangled_name = __cxxabiv1::__cxa_demangle(typeid(T).name(), nullptr, nullptr, &status);
+
   std::string className =
-      __cxxabiv1::__cxa_demangle(typeid(T).name(), nullptr, nullptr, &status);
+      (status == 0 && demangled_name != nullptr) ? demangled_name : typeid(T).name();
 
-  // Only one instance should exist, but it is possible for two instances
-  // to co-exist during a reload.
   assertWithMessage(
-      instanceCount_ <= 1,
+      instanceCount_.load() <= 1,
       "[Reanimated] More than one instance of " + className +
           " present. This may indicate a memory leak due to a retain cycle.");
 
-  instanceCount_++;
+  instanceCount_.fetch_add(1);
+
+  free(demangled_name);
 }
 
 template <class T>
 SingleInstanceChecker<T>::~SingleInstanceChecker() {
-  instanceCount_--;
+  instanceCount_.fetch_sub(1);
 }
 
 } // namespace reanimated

The leaks are gone. I have no idea what I’m doing so I don’t know if there are any side effects. Just thought it would be nice to share.

edit: the memory is still retained, at least it’s not leaking.

Hey everyone, I confirmed that we are aiming to take a look at this issue. However, it’s not on the top of our priorities for now. It will probably come up in July. Stay tuned!

Hey @MehediH 👋 I definitely agree that this is an important issue and we want to address it in the future, but currently, we’re running out of team capacity to handle it right now. We need more time 😕

Hey @avivash we are currently researching issues related to performance - but not this exact topic yet. If anything changes I will let you know! And, of course, I will always encourage trying to find the culprit yourself 😄

@efstathiosntonas You are correct. We were using react-native-fast-image and switching to Expo Image solved the memory leak issue. Now when components are unmounted, they actually release the memory.

Note that https://github.com/DylanVann/react-native-fast-image doesn’t use reanimated, so I am not sure why using Expo Image fixes the issue for us.

@PEZO19 hi, haven’t used it in production since I have no clue if what chatgpt proposed has any side effects in other parts of reanimated, I just posted that for testing purposes or to give some possible hints to SW devs.

Could this issue be related to the app freezing issue on Android with the useSharedValue issue ?