For the code below: (1) \"main\" calls a function \"f1\". (2) function \"f1\" does some number crunching; creates an array of \"char\" with mal
Yes, memory allocated with malloc()
stays until it is freed. How else could a function ever return variable-sized data to its caller?
When a program exits, all the memory it allocated with malloc()
is freed. However, it's generally not a good idea to keep lots of unneeded memory around until the program terminates, as it can impact performance, or the system can run out of virtual memory. This can be a particular concern for long-running programs, their memory use sometimes keeps growing until they use of all the available virtual memory.
You call free()
on the pointer returned by the function. So in your case, main()
can do free(fData)
after it's done using the array.
This should all be covered in any C programming class or textbook.