Use of previously freed memory

ID

c.memory_management.use_after_free

Severity

high

Resource

Memory Management

Language

C / C++

Description

The use of previously-freed memory can have any number of adverse consequences, ranging from the corruption of valid data to the execution of arbitrary code, depending on the instantiation and timing of the flaw. The simplest way data corruption may occur involves the system’s reuse of the freed memory.

Rationale

The use of previously-freed memory can have any number of adverse consequences, ranging from the corruption of valid data to the execution of arbitrary code, depending on the instantiation and timing of the flaw. The simplest way data corruption may occur involves the system’s reuse of the freed memory.

The following code illustrates a vulnerable pattern detected by this rule:

	{
		bailout = 1;
		free(ptr);
	}
	if (bailout)
		fprintf(stderr, "error: %p\n", ptr);

	free(ptr);
	// VULNERABLE: Use of previously freed memory
	fprintf(stderr, "error: %p\n", ptr);
}

Remediation

Follow secure coding practices and review the references below for detailed remediation guidance.

Configuration

This detector does not need any configuration.