I have a C program like the one below. I am trying to write a wrapper on top of malloc
with the signature int myAlloc()
. This wrapper should return 1 on a successful memory allocation or return 0 if memory allocation fails.
#include <stdio.h>
#include <stdlib.h>
int myAlloc(void **ptr, int size)
{
*ptr = malloc(size);
if (!ptr)
return 0;
else
return 1;
}
void main()
{
int *p = NULL;
myAlloc(&p, sizeof(int));
printf("%d\n", *p);
}
When I compile this I get a warning saying "incompatible pointer type". How can I make it possible for this function to be called with any possible pointer type without receiving the warning?
Is it possible to remove the casting operation from the actual function call?
Update
I found the answer. Here is corrected code:
#include <stdio.h>
#include <stdlib.h>
int myAlloc(void *ptr,int size)
{
*(void **)ptr = malloc(size);
if (!ptr)
return 0;
else
return 1;
}
int main()
{
int *p = NULL;
myAlloc(&p, sizeof(int));
*p = 5;
printf("%d\n", *p);
return 1;
}