How can I allocate memory and return it to the calling function

Memory allocated with malloc does not persist outside function scope?

#include <stdio.h>
int func(int * b) {
        b = malloc(sizeof(int));
        *b = 5;
        printf("Value of *b is :%d\n", *b);
}
int main() {
        int *a;
        func(a);
        printf("Value of *a is :%d\n", *a);
        return 0;
}


what is output of the above program ?

Value of *b is :5
Value of *a is :0


The value of *a is not the same which is returned by func(). The problem is passing the value of the pointer currently holds, rather than the address of it. By passing the pointer value as you were, there was no way for the value malloc created to be stored into the pointer.
we can solve this in two way :

First Way :

#include <stdio.h>
int* func(){
        int *b;
        b = (int *)malloc(sizeof(int));
        *b = 5;
        return b;
}
int main(){
        int *a;
        a = func();
        printf("%d", *a);
        free(a);
        return 0;
}


Second Way:

#include <stdio.h>
int* func(int **b){
        *b = (int *)malloc(sizeof(int));
        **b = 5;
        return *b;
}
int main(){
        int *a;
        func(&a);
        printf("%d", *a);
        free(a);
        return 0;
}


Output :  Output of above both program is 5.

No comments:

Post a Comment