Good ways to return string from function in C

Lynx Chang
1 min readFeb 5, 2020

--

❧ Pass size to function

Explanation

User pass the size of the buffer to the function, and return an error code if the size is not enough.

Example

snprintf(3) — Linux man page

int snprintf(char *str, size_t size, const char *format, ...);

❧ Return pointer

Explanation

Function allocate a block of memory. You can use alloc(), malloc(), calloc(), etc.

Example

strdup(3) — Linux man page

char *strdup(const char *s);

❧ Define maximum size

Explanation

Define a maximum size in library header.

Example

Openssl defined EVP_MAX_MD_SIZE, and user always allocate that size for buffer. When user call EVP_DigestFinal_ex(), it return actual used size. (Ref: EVP_DigestFinal)

int EVP_DigestFinal(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s);

❧ Use the same size_t pointer for input and output

Explanation

  • User fill in the buffer size so that the function can check the valid size of the buffer.
  • The function will fill in the actual buffer size.

Example

Function design: (return success or fail)

bool function(char *output_buf, size_t *output_buf_size)

Function use:

char buf[20];
size_t buf_sz = sizeof(buf);
bool ret = function(buf, &buf_sz);
if (ret) {
// valid output size is in buf_sz
}

❧ Summary

  • With a sound function design, don’t let logic go everywhere.
  • Reduce the interdependence between functions, and it will be faster and have fewer side effects in maintenance and modification in response to changes.
  • Don’t over-design, make simple things too complicated, but reduce the ease of maintenance and corresponding changes.
  • Staying flexible and understanding the high-level goals of the program will be a design consideration.

--

--