0

i'm trying to use a little bit of code to log mallocs in tcpdump for a project of mine, the code i'm using is thus:

#include <stdlib.h>


unsigned int memCount = 0;

void *my_malloc(size_t size) {
void *p = malloc(size);
memCount = memCount + size;
printf("Memory Allocated :%u \n", size
return p;
}

#define malloc(size) my_malloc(size)

After looking at many similar questions online it seems that this should work, however my custom malloc does not seem to be getting called. Any help would be much appreciated, thanks!

g_dow
  • 1
  • 1
  • 1
    Check this: http://stackoverflow.com/questions/262439/create-a-wrapper-function-for-malloc-and-free-in-c – LihO Mar 14 '12 at 12:52
  • are you overriding `malloc` in your code or already compiled code? also, make sure your macro is defined at a global level, being visible to every use of `malloc` – Necrolis Mar 14 '12 at 12:52

3 Answers3

1

You have to #define the malloc macro in each source file again - thus do it by including a header file where the macro is defined.

ckruse
  • 9,642
  • 1
  • 25
  • 25
  • This is not the problem. The problem is that the `my_malloc` ends up calling itself. – Mike Kwan Mar 14 '12 at 13:01
  • This is not what the OP asked, sorry. However, just don't ``#include`` that header file in the source file defining ``my_malloc()``, instead ``#include`` the ``stdlib.h`` file. Also be aware that you have to include the header file re-defining ``malloc()`` _after_ the ``stdlib.h``. – ckruse Mar 14 '12 at 13:03
0

It should, you're probably not making the define visible to the file you're actually using malloc in. Put it in a common header, that is included by all your implementation files.

EDIT: If the problem is the function is calling itself, you should move the define after the function declaration.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

Your problem is that your #define for malloc is called by your my_malloc when you are expecting the real malloc to be called. The reason for that is that the preprocessor also converted the malloc in there to my_malloc.

If we simply preprocess the following:

#define malloc(size) my_malloc(size)

unsigned int memCount = 0;

void *my_malloc(size_t size) {
  void *p = malloc(size);
  memCount = memCount + size;
  printf("Memory Allocated :%zu \n", size);
  return p;
}

int main(void) {
  malloc(123);
  return EXIT_SUCCESS;
}

You'll actually get:

unsigned int memCount = 0;

void *my_malloc(size_t size) {
  void *p = my_malloc(size);
  memCount = memCount + size;
  printf("Memory Allocated :%zu \n", size);
  return p;
}

int main(void) {
  my_malloc(123);
  return 0;
}

You need to access the real malloc, which is demonstrated here.

Community
  • 1
  • 1
Mike Kwan
  • 24,123
  • 12
  • 63
  • 96