I’m experimenting with writing malloc and free wrappers, and I wonder why does the following code gives error pointer being freed was not allocated, why does not delete() work?
#include <stdio.h>
#include <stdlib.h>
#define log(v) printf(#v " == %d \n", v)
#define new(n, type) _new((n), sizeof(type), __LINE__, __FILE__)
void *_new(int n, size_t size, int line, char *file)
{
int *ptr;
ptr = malloc(n * size);
if (ptr == NULL)
{
printf("new(): Memory allocation error, file \"%s\", line %d. \n", file, line);
exit(EXIT_FAILURE);
}
return ptr;
}
void delete(int *ptr)
{
free(*ptr);
*ptr = NULL;
}
main()
{
int *p;
p = new(1, int);
log(p);
delete(&p);
log(p);
}
Since you,
Then you should