I've reached this situation several times and just want to get some general advice.
I want to perform a call to malloc which allocates the exact number of bytes of a file on disk. One issue is that ftell() returns a long but malloc takes a size_t. I feel like the naive but obvious approach is to just do something like this:
The issue here is if ftell returns -1, this is not a good situation for malloc. Another issue is that the user can control directly how much is malloc'd by feeding various size files into the parser, potentially mallocing a HUGE amount of memory. Of course for this second problem, I could decide on a max # of bytes and create some logic to prevent a huge allocation. But I'm not sure on how to gather info to make this decision.Code:long filesize = ftell(fp); char *database = malloc((size_t)filesize);
What are some better methods of accomplishing memory allocation based off of disk file size? I just need to map a database from disk to memory. I work as a security engineer professionally and I've seen some of the other engineers do a ftell output directly to a malloc but it created some security issues a few times, however, I've not yet discovered a better way of doing this aside from the aforementioned.
Last but not least, can someone explain some background on some of these C functions with different return types? For example, I would expect ftell to return a size_t but it returns a long. I've noticed this is the case with several C library functions and it makes programming in C tricky at times until of course one has learned how to deal with each of these specific conversion situations. I assume that the long may be due to the large number of bytes that could be output from ftell, but then again, why not unsigned long or long long?
Thank you.