Объясните вывод, полученный с помощью следующего макроса - PullRequest
0 голосов
/ 06 сентября 2018
#include <stdio.h>

#define ABC(x) DEF(x)
#define DEF(x) GHI(x)
#define GHI(x) printf(x)

int main(void)
{
  int x = 100;
  int y = 200;
  ABC(("Sum of x + y is %d", x + y));

  return 0;
}

Вывод вышеуказанного кода дает Недопустимая ссылка на память (SIGSEGV) .

1 Ответ

0 голосов
/ 06 сентября 2018

Если бы вы рассмотрели предупреждения, вы могли бы идентифицировать себя

macro1.c: In function ‘main’:
macro1.c:11:3: warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast [enabled by default]
   ABC(("Sum of x + y is %d", x + y));
   ^
In file included from macro1.c:1:0:
/usr/include/stdio.h:362:12: note: expected ‘const char * __restrict__’ but argument is of type ‘int’
 extern int printf (const char *__restrict __format, ...);
            ^
macro1.c:11:3: warning: format not a string literal and no format arguments [-Wformat-security]
   ABC(("Sum of x + y is %d", x + y));

Это ясно указывает на то, что вы передаете int вместо string на printf. Потому что ваш код будет выглядеть ниже после предварительной обработки.

printf(("Sum of x + y is %d", x + y))

Чтобы все заработало, вы можете сделать, как показано ниже.

#include <stdio.h>

#define ABC(x,y) DEF(x,y)
#define DEF(x,y) GHI(x,y)
#define GHI(x,y) printf(x,y)

int main(void)
{
  int x = 100;
  int y = 200;
  ABC("Sum of x + y is %d", x + y);

  return 0;
}

или вы можете удалить скобки вокруг x в printf

#include <stdio.h>

#define ABC(x) DEF(x)
#define DEF(x) GHI(x)
#define GHI(x) printf x

int main(void)
{
  int x = 100;
  int y = 200;
  ABC(("Sum of x + y is %d", x + y));

  return 0;
} 
...