The code for this recipe is available at https://github.com/dev-cafe/cmake-cookbook/tree/v1.0/chapter-04/recipe-05, and has a C++ example. The recipe is valid with CMake version 3.5 (and higher), and has been tested on GNU/Linux, macOS, and Windows.
Memory defects, such as writing to or reading from memory beyond allocated bounds, or memory leaks (memory that is allocated, but never released), can create nasty bugs that are difficult to track down, and it is useful to detect them early. Valgrind (http://valgrind.org) is a popular and versatile tool to detect memory defects and memory leaks, and in this recipe, we will use Valgrind to alert us about memory problems when running tests using CMake/CTest (see Chapter 14, Testing Dashboards, for a discussion of the related AddressSanitizer and ThreadSanitizer).