I see three problems with your code. First, to answer the question you posed, you should pass buffer
rather than *buffer
as the third argument to fscanf
. Neil's answer does a good job explaining why.
Second, you have a buffer overflow. fscanf
automatically appends a null terminating character to the scanned input. The buffer you give to fscanf
must have enough space for the scanned input and the null terminating character. If you want to scan 2,047 characters then your buffer needs to be 2,048 characters long.
Third, the new version of your code is the one with the memory leak. Your previous version had no leaks because the buffer there was allocated on the stack (or in static storage if it is a global variable). The stack space used by the buffer will be reclaimed when the function returns. Allocating the buffer from the heap by using malloc
means that you are responsible for reclaiming the allocated heap memory by subsequently calling free
when you are finished with the buffer. In my opinion, your original version of the code, where you allocated buffer
on the stack, was much better.
The only case where the new version might be preferable is if you are targeting a system that has very limited stack space (as is the case with some embedded systems). On such systems, allocating a large buffer on the stack might not be a good idea. In such a case it may be preferable to allocate the buffer from the heap using malloc
, to avoid possible stack overflows. If that's the case then you must be careful to avoid memory leaks by calling free
to deallocate the memory.