A function returns without freeing memory it allocated and still holds only in a local variable

tx0/c:leak-on-early-returnrecommendedwarningbug, cwe-401

What it finds

p = malloc(n); if (len > max) return -1;: the function leaves before p is freed or stored anywhere, and the only pointer to the block is gone with the local variable.

The allocation must be stored in a local variable of the function, and the return must come in a later statement of the same block, or as the last statement of the body of an if there, with nothing in between that might give the pointer away: the statements in between may use the memory through it, pass it to functions of the C library that do not keep it, such as memcpy and strlen, and test it for NULL, and nothing else. Neither the return value nor the body of the if may mention it.

From the rule's source, leak_on_early_return.rs.

Example from the rule's tests
#include <stdlib.h>#include <string.h> void keep(char *p); int parse(const char *text, int max){  char *buf = malloc(64);  if (buf == NULL)    return -1;  memset(buf, 0, 64);  if (strlen(text) > (unsigned long)max)    return -2;tx0 reports: this returns without freeing buf  free(buf);  return 0;} int forgotten(int n){  char *p = malloc(n);  if (!p)    return -1;  p[0] = 0;  return 0;tx0 reports: this returns without freeing p} int given(int n){  char *p = malloc(n);  keep(p);  if (n > 4)    return -1;  return 0;} char *returned(int n){  char *p = malloc(n);  return p;}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/c:leak-on-early-return" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/c:leak-on-early-return] reason="..."

tx0 explain tx0/c:leak-on-early-return shows the same in the terminal. Found a false positive? Report it.