Wesley.Chung Wesley.Chung - 1 month ago 12
C Question

Dynamic array and functionalize malloc

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!

Answer

The pointer var is allocated memory dynamically but it is local to the function malloc_and_check. The pointer pi in the function main will not get to know the address of the memory allocated to var. It is a bad access and may also result in crash sometimes.

try the code below to get the expected results :

#include <stdio.h>
 #include <stdlib.h>

 void malloc_and_check(int *var)
 {
     int *var1;
     if(!(var1 = (int*)malloc(sizeof(int))))
     {
        fprintf(stderr, "Insufficient Memory\n");
        exit(EXIT_FAILURE);
     } 
     else 
        *var = var1;
 }

 int main(int argc, const char * argv[]) 
 {
    int *pi;
    malloc_and_check(&pi);
    *pi = 5;
    printf("%d", *pi);
    free(pi);
 }