It depends on what you want to do with the buffer.
Globals should usually be avoided, you should be very careful not to fall for the problems that arise with them.
If the buffer is needed in only one function, and BUFSIZE is not too large (max. Max.), You can make it local. However, keep an eye on the overall use of the stack as nested calls add up. Static local access is only needed when you want to keep values ββbetween calls, effectively making it global with the local scope. But it will give you headaches when you go multithreading or want to use recursion.
If the buffer is used for function calls or BUFSIZE is large enough, use malloc () / free (). If a function is called frequently, it might be a good idea to allocate it outside the function, make all function calls, and then free it instead of allocating and freeing another buffer for each function call. But this is almost a premature optimization, because it unnecessarily links the internal structure of the function with the external subscriber.
In an enlarged picture, when your program grows, you want to give it more structure and clearly define responsibilities, especially. to process memory, otherwise you will end up losing track. This buffer is a working part of a specific module with a specific task. A typical approach is to use a structure to organize data using the OOP method using the create and destroy functions to isolate and free such an object. The buffer can then be part of this structure.
struct s_foo { char buf[BUFSIZE]; ... }; struct s_foo *foo_create (...); void foo_destroy (struct s_foo *foo); void foo_action (struct s_foo *foo);
This allows you to have any number of phosphes in parallel, each with its own buffer, independently of each other. In addition, the contents of the buffer are preserved between calls without the headaches of a static variable.
source share