Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: REM Cost Reform

The C Standard, subclause 7.21.8.2 [ISO/IEC 9899:2011], defines the fwrite() function as follows:

...

Code Block
bgColor#ffcccc
langc
#include <stdio.h>
#include <stdlib.h>
char *buffer = NULL;
size_t size1,;
size_t size2;
FILE *filedes;

/*
 * Assume size1 and size2 are appropriately initialized
 */

filedes = fopen("out.txt", "w+");
if (filedes == NULL) {
  /* Handle error */
}

buffer = (char *)calloc( 1, size1);
if (buffer == NULL) {
  /* Handle error */
}

fwrite(buffer, 1, size2, filedes);

free(buffer);
buffer = NULL;
fclose(filedes);

...

This compliant solution ensures that the correct number of characters are written to the file.:

Code Block
bgColor#ccccff
langc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char *buffer = NULL;
size_t size1,;
size_t size2;
FILE *filedes;

/*
 * Assume size1 is appropriately initialized
 */

filedes = fopen("out.txt", "w+");
if (filedes == NULL){
  /* Handle error */
}

buffer = (char *)calloc( 1, size1);
if (buffer == NULL) {
  /* Handle error */
}

/*
 * Accept characters in to the buffer.
 * Check for buffer overflow.
 */

size2 = strlen(buffer) + 1;

fwrite(buffer, 1, size2, filedes);

free(buffer);
buffer = NULL;
fclose(filedes);

...

Failure to follow the recommendation could result in a non-null-terminated string being written to a file. This , which will create problems when the program tries to read it back as a null-terminated byte string.

Recommendation

Severity

Likelihood

Detectable

Remediation Cost

Repairable

Priority

Level

FIO18-C

Medium

Probable

Medium

P8

No

No

P4

L3

Automated Detection

Tool

Version

Checker

Description

LDRA tool suite
Include Page
LDRA_V
LDRA_V
44 SEnhanced enforcement
L2

Related Guidelines

Bibliography

[ISO/IEC 9899:2011]
Section
Subclause 7.21.8.2, "The fwrite Function"
[
Open Group 2004
IEEE Std 1003.1:2013]XSH, System Interfaces, fwrite


...

Image Modified Image Modified Image Modified