2248
Effectiveness = Defense in Depth
Demonstrative Examples
Example 1:
This example attempts to close a file twice. In some cases, the C library fclose() function will catch
the error and return an error code. In other implementations, a double-free (CWE-415) occurs,
causing the program to fault. Note that the examples presented here are simplistic, and double
fclose() calls will frequently be spread around a program, making them more difficult to find during
code reviews.
Example Language: C (Bad)
char b[2000];
FILE *f = fopen("dbl_cls.c", "r");
if (f)
{
b[0] = 0;
fread(b, 1, sizeof(b) - 1, f);
printf("%s\n'", b);
int r1 = fclose(f);
printf("\n-----------------\n1 close done '%d'\n", r1);
int r2 = fclose(f); // Double close
printf("2 close done '%d'\n", r2);
}
There are multiple possible fixes. This fix only has one call to fclose(), which is typically the
preferred handling of this problem - but this simplistic method is not always possible.
Example Language: C (Good)
char b[2000];
FILE *f = fopen("dbl_cls.c", "r");
if (f)
{
b[0] = 0;
fread(b, 1, sizeof(b) - 1, f);
printf("%s\n'", b);
int r = fclose(f);
printf("\n-----------------\n1 close done '%d'\n", r);
}
This fix uses a flag to call fclose() only once. Note that this flag is explicit. The variable "f" could
also have been used as it will be either NULL if the file is not able to be opened or a valid pointer
if the file was successfully opened. If "f" is replacing "f_flg" then "f" would need to be set to NULL
after the first fclose() call so the second fclose call would never be executed.
Example Language: C (Good)
char b[2000];
int f_flg = 0;
FILE *f = fopen("dbl_cls.c", "r");
if (f)
{
f_flg = 1;
b[0] = 0;
fread(b, 1, sizeof(b) - 1, f);
printf("%s\n'", b);
if (f_flg)
{
int r1 = fclose(f);
f_flg = 0;
printf("\n-----------------\n1 close done '%d'\n", r1);
}
if (f_flg)
CWE Version 4.14
CWE-1341: Multiple Releases of Same Resource or Handle
CWE-1341: Multiple Releases of Same Resource or Handle