Skip to content

Instantly share code, notes, and snippets.

@dimitarcl
Created October 18, 2018 06:12
Show Gist options
  • Save dimitarcl/002c745f97ec4472dbbbbd911da3559e to your computer and use it in GitHub Desktop.
Save dimitarcl/002c745f97ec4472dbbbbd911da3559e to your computer and use it in GitHub Desktop.
Xcode 9+ operator new
#include <string>
#include <cstdio>
void* operator new(size_t s)
{
auto p = std::malloc(s);
std::printf("lib alloc %p - %d\n", p, int(s));
return p;
}
void operator delete(void* p) noexcept
{
std::printf("lib free %p\n", p);
std::free(p);
}
void do_stuff(const char* x)
{
std::string temp(x);
std::printf("STR %s\n", temp.c_str());
}
#include <string>
void do_stuff(const char*);
#if defined(MAIN_NEW)
void* operator new(size_t s)
{
auto p = std::malloc(s);
std::printf("main alloc %p - %d\n", p, int(s));
return p;
}
void operator delete(void* p) noexcept
{
std::printf("main free %p\n", p);
std::free(p);
}
#endif
int main()
{
std::string x(42, 'x');
do_stuff(x.c_str());
return 0;
}
all: clean a.out test
liblib.dylib: lib.cc unexported.txt
clang++ ${CXXFLAGS} -std=c++14 -dynamiclib -single_module lib.cc -o liblib.dylib -Wall -Wl,-unexported_symbols_list,unexported.txt
a.out: main.cc liblib.dylib
clang++ ${CXXFLAGS} -std=c++14 main.cc -llib -L .
clean:
rm -f a.out liblib.dylib
test:
./a.out
@dimitarcl
Copy link
Author

Run

make
make CXXFLAGS=-O3
make CXXFLAGS=-DMAIN_NEW
make CXXFLAGS=-DMAIN_NEW\ -O3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment