Is it a bad practice to hide memory allocation in functions?

Should I expect the user to provide a piece of memory of sufficient size, say, to copy the file to the buffer? Or should I allocate the memory myself and expect the user to free it when they are done? For example, a function strdup()allocates memory itself, but a function fread()expects only a buffer of sufficient size.

+4
source share
3 answers

It depends - I saw that the C API uses all types of templates for this, for example:

  • which require the size of the buffer and buffer to be provided, and return the required size (so that you can adjust the size of the buffer if it has been truncated); many of them allow you to pass NULLas a buffer if you just ask how big the buffer should be; this allows the caller to use the existing buffer or to assign the appropriate size, albeit with two calls;
  • separate functions for obtaining the required size and filling the buffer; as above, but with a more intuitive interface;
  • which require the size of the buffer and the buffer, but can allocate the buffer themselves, if NULLpassed as a buffer; maximum flexibility and astringency, but the signature of the function may be confused;
  • , ; , - , , ; , , , , ;
  • , , ; , ; ( ), .

, , - ; , , - , . , , .

, , / , , - ? , ? ? ? , ?

, , , ; , , dll/so, ( free), C runtime . , C - , , .

+5

?

.

, , , , .


, , , .

getline(), . , stdin, , - . - .

, ssize_t getline_limit(char **lineptr, size_t *n, FILE *stream, size_t limit);, , .

#define LIMIT 1000000
char *line = NULL;
size_t len = 0;
ssize_t nread;

while ((nread = getline_limit(&line, &len, stdin, LIMIT)) != -1) {

, , .

// Convert `double` to its decimal character representation allocating a right-size buffer
// At worst a few thousand characters
char *double_to_string_exact_alloc(int x)

, , , .

+3

C . , strdup , scanf C .

You can choose any method in your library. Using pre-allocated buffers is more flexible as it allows users to pass statically distributed buffers to you. This flexibility comes at a cost because the user code becomes more verbose.

If you decide to allocate memory for a custom structure dynamically, it is recommended that you create an appropriate function to free the structure after it becomes unnecessary for the user.

+2
source

Source: https://habr.com/ru/post/1685116/


All Articles