0

I want to replace the sprintf() to snprintf() of my project. So I write a shell to replace sprintf() to MY_SPRINTF and then,

#define MY_SPRINTF(buf,args...)  snprintf(buf,sizeof(buf), ## args).

However, the parameter "buf" is a pointer somewhere in my project that make my replacement not work correctly.

I want to figure out whether the parameter "buf" is a pointer when compiling. Is it possible ?

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Litchi
  • 3
  • 1
  • If you can figure out the pointer cases, how are going to handle it? Just use snprintf for arrays and leave the pointer ones with sprintf? – P.P May 18 '15 at 13:12
  • I will use snprintf for arrays as well as pointer. However, I will check the pointer manually and detect the second parameter for snprintf. – Litchi May 19 '15 at 13:05

2 Answers2

2

You can't do it, you should not do it, just search for every occurrance of it and fix it accordingly.

If buf is an array it will work with sizeof() otherwise there is no way to know the size of the allocated pointer.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • I'll admit to having no experience with them myself but I _thought_ you could do this with C11 generics, i.e. `#define MY_SPRINTF(buf, args...) (_Generic((buf), char *: sprintf((buf), ## args), default: snprintf((buf), sizeof(buf), ## args)))` or something along those lines – doynax May 18 '15 at 14:42
0

I want to figure out whether the parameter "buf" is a pointer when compiling. Is it possible ?

Arrays and pointers can be distinguished during compile time, see the answers of this question. After you replaced sprintf by a MY_SPRINTF rejecting pointers the compiler halts when sprintf is used with a pointer so you need not to check every replacement manually.

#define ARRAY_SNPRINTF(buf,...)  \
    snprintf(buf,_Generic(&buf, char (*)[]:sizeof(buf),default:(void)0), __VA_ARGS__)
Community
  • 1
  • 1
4566976
  • 2,419
  • 1
  • 10
  • 14
  • Thanks a lot. I would like to use [link](http://stackoverflow.com/questions/19452971/array-size-macro-that-rejects-pointers) to do that. – Litchi May 19 '15 at 13:48
  • @Litchi: added an example macro (C11) to my answer. – 4566976 May 19 '15 at 17:32