Search code examples
c++pointersmallocdynamic-memory-allocationdereference

Dynamic Memory Allocation using malloc


    # include<stdio.h> 
# include<stdlib.h> 
   
void fun(int *a) 
{ 
    a = (int*)malloc(sizeof(int)); 
} 
   
int main() 
{ 
    int *p; 
    fun(p); 
    *p = 6; 
    printf("%d\n",*p); 
    return(0); 
}

Why is the above code not valid ? And why does it give a segmentation fault?


Solution

  • Because a is passed by-value itself, then any modification on itself in the function has nothing to do with the argument.

    You can change it to pass-by-reference as

    void fun(int *&a) 
    { 
        a = (int*)malloc(sizeof(int)); 
    } 
    

    BTW: In C++ better to use new (and delete), or don't use raw pointers from the beginning.