I try to malloc an array functionally, and this function also can check whether the memory is enough or not.
The first code block can't work.
When it executes " *pi = 5
", the compiler shows this error message " Thread 1: EXC_BAD_ACCESS(code=1, address=0x0) "
.
#include <stdio.h>
#include <stdlib.h>
void malloc_and_check(int *var)
{
if(!(var = (int*)malloc(sizeof(int))))
{
fprintf(stderr, "Insufficient Memory\n");
exit(EXIT_FAILURE);
}
}
int main(int argc, const char * argv[])
{
int *pi;
malloc_and_check(pi);
*pi = 5;
printf("%d", *pi);
free(pi);
}
However, the codes as below can work normally.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[])
{
int *pi;
if(!(pi = (int*)malloc(sizeof(int))))
{
fprintf(stderr, "Insufficient Memory\n");
exit(EXIT_FAILURE);
}
*pi = 5;
printf("%d", *pi);
free(pi);
}
What are the difference between them? Thanks!