> If you malloc() 42 bytes then tell
> fgets() to read 42 bytes, it is impossible
> to overflow the buffer, so is very safe.

In the case of fgets(), a terminating '\0' is helpfully 
included in the count, unlike most string functions where a 
string of n chars needs storage of n+1 chars. This means 
that fgets(buffer, n, stream) will only get n-1 characters, 
so there's the possibility of an out-by-one error. But at 
least it's safe.

>> Ordinarily when your program exits, any
>> memory it allocated will be freed.

> Is that OS/environment-dependent?

Program termination, by whatever means, is supposed to 
involve tidying up, including returning any memory back to 
the operating system. It's the compiler's duty to make sure 
this happens, via the runtime wrapper it puts around your 
program. So it's compiler-dependent rather than 
OS-dependent.

However, a sensibly designed OS would also ensure that when 
a process terminates, its resources are reclaimed, forcibly 
if necessary.

David

Reply via email to