How do I capture a smart pointer in a lambda?

Viewed 10511

What is best way to capture a smart pointer in a lambda? One attempt of mine lead to a use-after-free bug.

Example code:

#include <cstring>
#include <functional>
#include <memory>
#include <iostream>

std::function<const char *(const char *)> test(const char *input);

int main()
{
  std::cout.sync_with_stdio(false);
  std::function<const char *(const char *)> a = test("I love you");
  const char *c;
  while ((c = a(" "))){
    std::cout << c << std::endl;
  }
  return 0;
}
std::function<const char *(const char *)> test(const char *input)
{
  char* stored = strdup(input);
  char *tmpstorage = nullptr;
  std::shared_ptr<char> pointer = std::shared_ptr<char>(stored, free);
  return [=](const char * delim) mutable -> const char *
  {
    const char *b = strtok_r(stored, delim, &tmpstorage);
    stored = nullptr;
    return b;
  };
}

fails, as shown by AddressSanitizer.

2 Answers
Related