I just found another way to replace the memcpy
function call. It only works with GCC(I still need to find another way for VC++) but I think it's definitely better than the crude #define
way. It uses the __REDIRECT
macro(in sys/cdefs.h
included via features.h
), which from what I've seen it's used extensively in the glibc. Below follows an example with a small test:
// modified.h
#pragma once
#ifndef MODIF_H_INCLUDED_
#define MODIF_H_INCLUDED_
#include <cstddef>
#include <features.h>
extern "C"
{
void test_memcpy(void* __restrict to, const void* __restrict from, size_t size);
}
#if defined(__GNUC__)
void __REDIRECT(memcpy, (void* __restrict to, const void* __restrict from, size_t size),
test_memcpy);
#endif /* __GNUC__ */
#endif /* MODIF_H_INCLUDED_ */
//modified.cpp
extern "C" void test_memcpy(void* __restrict to, const void* __restrict from,
size_t size)
{
std::cout << "Dumb memcpy replacement!\n";
}
//original.h
#pragma once
#ifndef ORIG_H_INCLUDED_
#define ORIG_H_INCLUDED_
void test_with_orig();
#endif /* ORIG_H_INCLUDED_ */
//original.cpp
#include <cstring>
#include <iostream>
void test_with_orig()
{
int* testDest = new int[10];
int* testSrc = new int[10];
for (unsigned int i = 0; i < 10; ++i)
{
testSrc[i] = i;
}
memcpy(testDest, testSrc, 10 * sizeof(int));
for (unsigned int i = 0; i < 10; ++i)
{
std::cout << std::hex << "\nAfter standard memcpy - "
<< "Source: " << testSrc[i] << "\tDest: " << testDest[i] << "\n";
}
}
// and a small test
#include "modified.h"
#include "original.h"
#include <iostream>
#include <cstring>
int main()
{
int* testDest = new int[10];
int* testSrc = new int[10];
for (unsigned int i = 0; i < 10; ++i)
{
testSrc[i] = i;
testDest[i] = 0xDEADBEEF;
}
memcpy(testDest, testSrc, 10 * sizeof(int));
for (unsigned int i = 0; i < 10; ++i)
{
std::cout << std::hex << "\nAfter memcpy replacement - "
<< "Source: " << testSrc[i] << "\tDest: " << testDest[i] << "\n";
}
test_with_orig();
return 0;
}