A
arnuld
At my job, I am working on a piece of code (around 16 source files)
where I have to call malloc() and free() around 20 times. Every time I
have to check the return value of malloc(). So I cam up with this idea
of writing my own malloc() and then using it. is this a good idea ?
#include <stdio.h>
#include <stdlib.h>
enum { ARRSIZE = 10 };
struct my_struct
{
int i;
char arrc[ARRSIZE];
};
void* malloc_my_struct(int num, size_t s);
void free_my_struct( struct my_struct** p );
int main(void)
{
struct my_struct* m = malloc_my_struct(1, sizeof(*m));
printf("Memory allocated: %p\n", (void*)m);
free_my_struct(&m);
printf("Memory freed: %p\n", (void*)m);
return 0;
}
void* malloc_my_struct(int num, size_t s)
{
void* p = malloc(num * s);
if(NULL == p) fprintf(stderr, "IN: %s: Memory Exhausted, can not
allocate more memory\n", __func__);
return p;
}
void free_my_struct( struct my_struct** p )
{
free(*p);
*p = NULL;
}
============ OUTPUT ======================
[arnuld@dune programs]$ gcc -std=c99 -pedantic -Wall -Wextra xmalloc.c
[arnuld@dune programs]$ ./a.out
Memory allocated: 0x804a008
Memory freed: (nil)
[arnuld@dune programs]$
I got this idea actually from GNU C Library manual:
http://www.gnu.org/software/hello/manual/libc/Malloc-Examples.html#Malloc-Examples
.. 2md, I am using -std=c99 rather than -ansi flag because I am unable
to find any alternative to __func__ . Do you know any ?
where I have to call malloc() and free() around 20 times. Every time I
have to check the return value of malloc(). So I cam up with this idea
of writing my own malloc() and then using it. is this a good idea ?
#include <stdio.h>
#include <stdlib.h>
enum { ARRSIZE = 10 };
struct my_struct
{
int i;
char arrc[ARRSIZE];
};
void* malloc_my_struct(int num, size_t s);
void free_my_struct( struct my_struct** p );
int main(void)
{
struct my_struct* m = malloc_my_struct(1, sizeof(*m));
printf("Memory allocated: %p\n", (void*)m);
free_my_struct(&m);
printf("Memory freed: %p\n", (void*)m);
return 0;
}
void* malloc_my_struct(int num, size_t s)
{
void* p = malloc(num * s);
if(NULL == p) fprintf(stderr, "IN: %s: Memory Exhausted, can not
allocate more memory\n", __func__);
return p;
}
void free_my_struct( struct my_struct** p )
{
free(*p);
*p = NULL;
}
============ OUTPUT ======================
[arnuld@dune programs]$ gcc -std=c99 -pedantic -Wall -Wextra xmalloc.c
[arnuld@dune programs]$ ./a.out
Memory allocated: 0x804a008
Memory freed: (nil)
[arnuld@dune programs]$
I got this idea actually from GNU C Library manual:
http://www.gnu.org/software/hello/manual/libc/Malloc-Examples.html#Malloc-Examples
.. 2md, I am using -std=c99 rather than -ansi flag because I am unable
to find any alternative to __func__ . Do you know any ?