Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Many existing functions that return errno are declared as returning a value of type int. It is semantically unclear by looking at the function declaration or prototype if these functions return an error status or a value or, worse, some combination of the two. (See ERR02-C. Avoid in-band error indicators.)

TR 24731-1 introduced C11 Annex K  introduced the new type errno_t that is defined to be type int in errno.h and elsewhere. Many of the functions defined in TR 24731-1 C11 Annex K return values of this type [TR 24731-1ISO/IEC 9899:2011]. The errno_t type should be used as the type of an object that may contain only values that might be found in errno. For example, a function that returns the value of errno should be declared as having the return type errno_t.

This recommendation depends on TR 24731-1 C11 Annex K being implemented and advocates using errno_t in new code where appropriate.

...

Code Block
bgColor#FFCCCC
langc
#include <errno.h>
#include <stdio.h>
 
enum { NO_FILE_POS_VALUES = 3 };

int opener(
  FILE *file,
  int *width,
  int *height,
  int *data_offset
) {
  int file_w;
  int file_h;
  int file_o;
  fpos_t offset;

  if (file == NULL) { return EINVAL; }
  errno = 0;
  if (fgetpos(file, &offset) != 0) { return errno; }
  if (fscanf(file, "%i %i %i", &file_w, &file_h, &file_o)
        != NO_FILE_POS_VALUES) {
    return EIO;
  }

  errno = 0;
  if (fsetpos(file, &offset) != 0) { return errno; }

  if (width != NULL) { *width = file_w; }
  if (height != NULL) { *height = file_h; }
  if (data_offset != NULL) { *data_offset = file_o; }

  return 0;
}

...

Code Block
bgColor#ccccff
langc
#include <errno.h>
#include <stdio.h>

enum { NO_FILE_POS_VALUES = 3 };

errno_t opener(
  FILE *file,
  int *width,
  int *height,
  int *data_offset
) {
  int file_w;
  int file_h;
  int file_o;
  fpos_t offset;

  if (file == NULL) { return EINVAL; }
  errno = 0;
  if (fgetpos(file, &offset) != 0 ) { return errno; }
  if (fscanf(file, "%i %i %i", &file_w, &file_h, &file_o)
        != NO_FILE_POS_VALUES) {
    return EIO;
  }

  errno = 0;
  if (fsetpos(file, &offset) != 0 ) { return errno; }

  if (width != NULL) { *width = file_w; }
  if (height != NULL) { *height = file_h; }
  if (data_offset != NULL) { *data_offset = file_o; }

  return 0;
}

...

CERT C++ Secure Coding StandardDCL09-CPP. Declare functions that return errno with a return type of errno_t
ISO/IEC TR 24731-1:20079899:2011K.3.2 Errors <errno.h> 
ISO/IEC TR 24772:2013Ignored Error Status and Unhandled Exceptions [OYB]
MISRA C:2012Directive 1.1 (required)

...