-
malloc & cover function
I want to write a cover function for malloc, so that each time malloc() is invoked, the program execute fmalloc() instead. In fmalloc() I will execute the real malloc(). How do I do that??
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (void)
{
char *pt,*lt,*gt;
pt=(char*)malloc(40);
if (pt==NULL)
{
perror("fmalloc");
exit(1);
}
lt=(char*)malloc(40);
if (lt==NULL)
{
perror("fmalloc");
exit(1);
}
gt=(char*)malloc(40);
if (gt==NULL)
{
perror("fmalloc");
exit(1);
}
strcpy(pt, "abcdefghijklmnopqrstuvxyz");
strcpy(lt, "abcdefghijklmnopqrstuvxyz");
strcpy(gt, "abcdefghijklmnopqrstuvxyz");
printf("Address allocated is %p\n",pt);
printf("Address allocated is %p\n",lt);
printf("Address allocated is %p\n",gt);
free(pt);
free(lt);
free(gt);
printf("Address freed is %p\n",pt);
printf("Address freed is %p\n",lt);
printf("Address freed is %p\n",gt);
return 0;
}
-
What do you mean, 'how do you do it'?
Code:
void *fmalloc( size_t s )
{
return malloc( s );
}
I don't understand what you aren't knowing how to do.
"Bob, I can 'do that code' in one line!"
"Quzah, do that code!"
#define fmalloc malloc
[edit]
I misunderstoold what you had intended. You shouldn't try and override standard functions. I mean I guess you can try, but it's bad practice. Especially if you're going to try and have reusable code at all.
[/edit]
Quzah.
-
Maybe something like the following would work.
Code:
#include<stdio.h>
#include<stdlib.h>
void *fmalloc(size_t size)
{
void *start = malloc(size);
if(start)
{
char *end = start;
end += size;
printf("fmalloc:%p-%p\n", start, end);
}
else
{
puts("fmalloc failed");
}
return(start);
}
#define malloc fmalloc
int main()
{
char *ptr = malloc(64);
free(ptr);
return 0;
}
/* my output
fmalloc:007A305C-007A309C
*/
-
I don't see anything too wrong with writing your own malloc. However, of the standard library functions malloc is probably the most frustrating to write.
-
>I don't see anything too wrong with writing your own malloc.
I do. Without very careful planning and use of a standard memory allocation routine you lose any vestige of portability. Writing a wrapper is far better:
Code:
void *fmalloc ( size_t size )
{
void *new_block;
new_block = malloc ( size );
if ( new_block == NULL ) {
fputs ( "Error allocating memory\n", stderr );
exit ( EXIT_FAILURE ); /* Or your favorite recovery routinte */
}
return new_block;
}
-Prelude