1.
Is the casting before calling the malloc function ever neccesary?
If you use a currect compiler, No. See answers to Do I cast the result of malloc?
2.
how do we know how much memory we need to allocate
It depends on your needs.
3.
malloc(10 * sizeof(int));
means to allocate memory big enough to store 10 int
value.
4.
is it multiplying 4 bytes by 10?
If sizeof(int)
equals 4, yes.
5.
when is it neccesary to use malloc?
If only at runtime you can know how much memory your program needs.
6.
How does it work internally?
Briefly, malloc()
will ask operating system for enough memory, record some information it needs, and return you a pointer to the start of that memory segment.