I have a question dedicated to:
void* malloc (size_t size);
In the regular example that can be found on millions of sites over the internet it's shown that the right way to use malloc is the following:
int main()
{
   int* num;
   num = malloc(sizeof(int));
   *num = 10;
   printf("Value = %d\n", *num);
   
   free(num);
   return 0;
}
But If I want to allocate memory within a function and use it in main like below, then the only option is to implement the function the following way:
void func_alloc(int** elem, int num_value)
{
    *elem = malloc(sizeof(int));
    **elem = num_value;
}
int main()
{
    int* num;
    func_alloc(&num, 10);
    free(num);
    return 0;
}
I assumed by mistake, that such code as below would work:
void func_alloc(int* elem, int num_value)
{
    elem = malloc(sizeof(int));
    *elem = num_value;
}
int main()
{
    int* num;
    
    func_alloc(num, 10);
    free(num);
    return 0;
}
Could you please explain or maybe give a link to resource with explanation why does it work only this way?
I really cannot understand why do I need double pointer as an input parameter and why in the other case it comes to "segmentation fault"...
Thank in advance ;)
 
     
     
    