Chan Kim
Chan Kim

Reputation: 5959

adding a statement after or before all specific function calls using define in C

I have done this before but somehow I can't do it now so I ask here. I have some codes I downloaded from a git repository and I want to print the filename, and linenumber whenever malloc is called. I made a simple test.

---- test.c ----
#include <stdlib.h>
#include <stdio.h>
#include "xxx.h"

main()
{
printf("hello\n");
int *ip = malloc(120*sizeof(int));
printf("ip = %x\n",ip);
free(ip);
}

---- xxx.h
#define malloc(x) do {malloc(x); \
printf("malloc at %s()-%d,%s\n",__func__,__LINE__,__FILE__);} \
while(0)

When I do gcc test.c, I get

test.c: In function 'main':
test.c:8: error: expected expression before 'do'

How should I fix xxx.h ? (this question applies also for C++)

Upvotes: 0

Views: 177

Answers (2)

John Bode
John Bode

Reputation: 123488

Given the macro, the line

int *ip = malloc(120*sizeof(int));

expands to

int *ip = do { malloc(120*sizeof(int)); printf("malloc at %s()-%d,%s\n",__func__,__LINE__,__FILE__);} while(0);

which hopefully makes it obvious where that error comes from.

John Zwinck's solution is a good option, although personally I'd create a wrapper function (named something other than malloc, naturally) rather than a macro.

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249273

Try this:

#define malloc(x) ( \
    printf("malloc at %s()-%d,%s\n",__func__,__LINE__,__FILE__), \
    malloc(x))

The idea is to use the "comma operator" like this:

int *ip = (printf(...), malloc(120*sizeof(int)));

The result of the comma operator is always its last argument.

Upvotes: 4

Related Questions