Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory allocated with malloc does not persist outside function scope?

Tags:

c

malloc

Hi,

I'm a bit new to C's malloc function, but from what I know it should store the value in the heap, so you can reference it with a pointer from outside the original scope. I created a test program that is supposed to do this but I keep getting the value 0, after running the program. What am I doing wrong?

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

int f1(int *b) {
    b = malloc(sizeof(int));
    *b = 5;
}

int main(void) {
    int *a;
    f1(a);
    printf("%d\n", a);
    return 0;
}

like image 522
PM. Avatar asked Mar 25 '10 05:03

PM.


People also ask

What is the scope of malloc?

void function(int *a) { a=(int *)malloc(sizeof(int)); Here, a is a local variable within function . Pointers are passed by value in C, so a receives a copy of the pointer in main when you do function(num); main() does not see that you assign to that local copy of the pointer.

Can you use malloc inside a function?

Memory allocation (malloc), is an in-built function in C. This function is used to assign a specified amount of memory for an array to be created. It also returns a pointer to the space allocated in memory using this function.


1 Answers

Yes! a is passed by value so the pointer b in function f1 will be local.. either return b,

int *f1() {
    int * b = malloc(sizeof(int));
    *b = 5;
    return b;
}

int main() {
    int * a;
    a = f1();
    printf("%d\n", *a);
    // keep it clean : 
    free(a);
    return 0;
}

or pass a's address

int f1(int ** b) {
    *b = malloc(sizeof(int)); 
    **b = 5;
}

int main() {
    int * a;
    f1(&a);
    printf("%d\n", *a);
    // keep it clean : 
    free(a);
    return 0;
}
like image 196
raj Avatar answered Oct 27 '22 00:10

raj