Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: code examples

...

Noncompliant Code Example

The asprintf() function has been provided by the GNU C library. It works like sprintf(), but if given a null pointer as the destination string, it will create a buffer sufficient to hold the resulting string. It relies on malloc() to allocate the buffer. If malloc() fails, then asprintf() returns a negative number.

This noncompliant code example calls fputsasprintf() and , but fails to check whether a write error occurs:the string was successfully created.

Code Block
bgColor#ffcccc
langc
FILE* f = /* output file stream */
/* ... */
fputs("foo", f);

...

void func(char* name) {
  char* s = NULL;
  asprintf(&s,"Hello, %s!\n", name);
  puts(s);
}

Compliant Solution

This compliant solution checks to make sure no output error occurred (see ERR33-C. Detect and handle standard library errors).

Code Block
bgColor#ccccff
langc
FILE* f = /* output file stream */
/* ... */
if (fputs("foo", f) == EOFvoid func(char* name) {
  char* s = NULL;
  if (asprintf(&s,"Hello, %s!\n", name) < 0) {
    /* Handle error */
  }
  puts(s);
} 

Exceptions

EXP12-C-EX1: If the return value is inconsequential or if any errors can be safely ignored, such as for functions called because of their side effects, the function should be explicitly cast to void to signify programmer intent. For an example of this exception, see "Compliant Solution (Remove Existing Destination File)" under the section "Portable Behavior" in FIO10-C. Take care when using the rename() function, or Exception ERR33-C-EX1 in ERR33-C. Detect and handle standard library errors.

...