0

I was asked to implement malloc and free.. I implememented those in my malloc.c file which includes malloc.h file and in malloc.h file I have these macro

 #define malloc( x ) mymalloc( x, __FILE__ , __LINE__ )
 #define free( x ) myfree( x, __FILE__ , __LINE__ )
 #define calloc( x,y ) mycalloc( x, y, __FILE__, __LINE__ )

Whenever I use malloc(10) or something in my main function, it says undefined reference to mymalloc

user3100209
  • 357
  • 1
  • 4
  • 17
  • 4
    gonna need a little more code than that buddy – Red Alert May 02 '14 at 21:16
  • @RedAlert Should I post malloc.c ? – user3100209 May 02 '14 at 21:17
  • 2
    Where is the code for mymalloc, myfree, mycalloc? Please read [How to Ask](http://stackoverflow.com/questions/how-to-ask). Remember you are asking people to spend their time on your problem. Help us help you. – Pablo Maurin May 02 '14 at 21:20
  • malloc.h and the main function where you use the macros should be enough. – Red Alert May 02 '14 at 21:21
  • 7
    Well if this if an "undefined reference" I think code won't help much, as this seems like a linker error. So you should probably present a way how you build your stuff too. – luk32 May 02 '14 at 21:28

2 Answers2

0

Under Linux (or cygwin under Windows), using gcc test.c malloc.c -o test, the following will work (execution with ./test)

test.c:

#include "malloc.h"
int main()
{
   malloc(10);
   return 0;
}

malloc.h:

#define malloc( x ) mymalloc( x, __FILE__ , __LINE__ )
int mymalloc(int x, char *file, int line);

malloc.c:

#include <stdio.h>

int mymalloc(int x, char *file, int line)
{
  printf("%s, line %d: %d", file, line, x);
  return 0;
}

EDIT: added the prototype of mymalloc to avoid a warning

daouzli
  • 15,288
  • 1
  • 18
  • 17
  • This shouldn't work without an error, or at least a warning, because `malloc.h` doesn't include a declaration for `mymalloc()`. Does it compile for you with no errors or warnings? – Dale Hagglund Aug 01 '14 at 06:19
  • @DaleHagglund this works just fine! You can compile it and run it... – daouzli Aug 01 '14 at 07:56
  • of course it is a better practice to add the prototype but it was not the problem of @user3100209 – daouzli Aug 01 '14 at 08:03
0

Note that a line like

p = malloc(10);

is expanded by the C preprocessor to

p = mymalloc(10, "this-file-name.c", /* current line number */);

and this line fails to compile because there's no declaration for mymalloc() visible to the compiler. You need to add the following lines to mymalloc.h.

void *mymalloc(int, const char *, int);
void myfree(void *, cont char *, int);
void *mycalloc(int, int, const char *, int);
Dale Hagglund
  • 16,074
  • 4
  • 30
  • 37