3

How can I make sure that if someone uses come specific function(say memcpy) in code, then it returns an error.

We have removed all the instances of memcpy from code with some internal designed function,

what I want to make sure is that whenever someone uses memcpy in future, the compiler throws an errors msg.

Sohrab Ahmad
  • 145
  • 3
  • 8

2 Answers2

5

You can use the preprocessor for this, like

#define memcpy(a, b, c) do_not_use_memcpy

Put that in a header file that is included in all source files, and the preprocessor will replace all calls to memcpy with the (undefined) symbol do_not_use_memcpy. As that symbol is undefined, you will get a compiler error about it.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • The problem with this approach is that the newly created function uses memcpy internally. – Sohrab Ahmad Jul 11 '13 at 11:09
  • +1 particularly nice in that it will give you a readable compiler warning containing the text "do_not_use_memcpy" – Bathsheba Jul 11 '13 at 11:09
  • @Sohrab Ahmad, undef and re-def it in the new function. – Bathsheba Jul 11 '13 at 11:10
  • @SohrabAhmad For that single place, undefine the macro with `#undef memcpy`. – Some programmer dude Jul 11 '13 at 11:10
  • It's sound dangerous to me because gcc may replace some loops to a call to the memcpy function. This is done through the tree-loop-distribute-patterns optimization in gcc 4.8. – Maxime Chéramy Jul 11 '13 at 11:30
  • 1
    @Maxime The code optimizations are done long after the preprocessor has run, so that won't be a problem. This doesn't actually replace the actual `memcpy` function, just changes the calls to it. – Some programmer dude Jul 11 '13 at 11:32
  • I see, but are you sure there won't be any call to the memcpy at the end? What about adding a `-fno-builtin-memcpy`? – Maxime Chéramy Jul 11 '13 at 11:41
  • 1
    @Maxime If that macro is in all translation units, then there won't be any explicit calls to `memcpy`. That flag just tells GCC that it should not use its own implementation of `memcpy`, and instead use the one in the standard library. – Some programmer dude Jul 11 '13 at 11:45
4

To avoid breaking libraries, use the deprecated attribute :

void * my_new_memcpy ( void * destination, const void * source, size_t num )
{
    return memcpy(destination, source, num);
} __attribute__((deprecated));

// Make sure this is used *after* declaring the function
#define memcpy my_new_memcpy
Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105