Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

How to get calling line number and file name

I am trying to log memory allocation. I want to be able to specify exactly which function call (line number and file name) called a particular function at runtime. Something like:

// overloading operator new
void* operator new [](std::size_t const count) {
  void* p = std::malloc(count);
  if (!p) throw std::bad_alloc{};
  std::cout << "Allocated " << count << " bytes in file '"
            << CALLING_FUNCTION_FILE_NAME << "'. Line "
            << CALLING_FUNCTION_LINE_NUMBER << '.\n';
  return p;
}

So that later on when I call it like:

// File sourceFileFoo.cpp

void foo() {               // line 41
    int* ip = new int[10]; // line 42
    delete[] ip;           // line 43
}                          // line 44

The output should be something like:

Allocated 40 bytes in file 'sourceFileFoo.cpp'. Line 42.

CALLING_FUNCTION_FILE_NAME expanded to the name of the file in which operator new was called (sourceFileFoo.cpp) and CALLING_FUNCTION_LINE_NUMBER expanded to the line in which operator new was called (42).

  1. I know this is going to be implementation specific if at all possible. I am working with Visual Studio and C++17.
  2. I cannot do something like define a macro NEW which does logging and then does allocation.

Upvotes: 0

Views: 331

Answers (1)

G.M.
G.M.

Reputation: 12899

As per the comment boost.stacktrace is probably what you're looking for. So, simplictically, your code would look something like...

#include <boost/stacktrace.hpp>

/*
 * overloading operator new
 */
void *operator new [](std::size_t const count)
{
  void *p = std::malloc(count);
  if (!p)
    throw std::bad_alloc{};
  std::cout << "Allocated " << count << " bytes at "
            << boost::stacktrace::stacktrace() << '.\n';
  return p;
}

Upvotes: 1

Related Questions