Versions Compared

Key

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

As noted in undefined behavior 179 of Annex J of the C standard Standard [ISO/IEC 9899:2011], the behavior a program is undefined when

...

Code Block
bgColor#FFCCCC
langc
/* p is a pointer to dynamically allocated memory */
p2 = realloc(p, size);
if (p2 == NULL) {
  free(p); /* p may be indeterminate when (size == 0) */
  return;
}

Section 7.22.3 of the C standard Standard [ISO/IEC 9899:2011] states:

If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.

and And Section 7.22.3.5 states:

If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged.

If realloc() is called with size equal to 0, then if a null pointer is returned, the old value should be unchanged. However, there are some common but nonconforming implementations that free the pointer, including the following:

  1. Glibc (GNU/Linux)
  2. AIX
  3. HP-UX
  4. Solaris
  5. OSF/1

...

Tool

Version

Checker

Description

LDRA tool suite

Include Page
LDRA_V
LDRA_V

484 S

Fully implemented.

Fortify SCA

V. 5.0

Double Free

 

Splint

Include Page
Splint_V
Splint_V
  

Coverity

Include Page
Coverity_V
Coverity_V

RESOURCE_LEAK

Finds resource leaks from variables that go out of scope while owning a resource.

Coverity

Include Page
Coverity_V
Coverity_V

USE_AFTER_FREE

Can find the instances where a freed memory is freed again. Coverity Prevent cannot discover all violations of this rule, so further verification is necessary.

Compass/ROSE

  

Can detect some violations of this rule. In particular, false positives may be raised if a variable is freed by a different function than the one that allocated it. Also, it is unable to warn on cases where a call to free() happens inside of a for loop.

Klocwork

Include Page
Klocwork_V
Klocwork_V

MLK
UFM.FFM

 

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

...

...

...

...

TR 24772:2013Dangling Reference to Heap [XYK]
Memory Leak [XYL]
ISO/IEC TS 17961 (Draft)Freeing memory multiple times [dblfree]

...

...

...

Double free

...

Bibliography

[ISO/IEC 9899:2011]Section 7.22.3, "Memory Management Functions"
[MIT 2005] 
[OWASP

...

Double Free]"Double Free"
[Viega 2005]"Doubly

...

Freeing Memory"
[VU#623332] 

 



 

...