A function returns the address of one of its local variables
What it finds
return &x; or return buf; for a local variable x or a local array buf: the variable ends with the function, so the caller gets a pointer to memory that is reused by the next call.
The variable must be declared in the function without static, extern or thread_local, in every branch of the conditional directives around it, and an array must have its brackets in its own declarator. The address of a field or an element of such a variable counts too, but not an element reached through a pointer.
From the rule's source, return_local_address.rs.
struct point { int x; int y;}; static int counter; int *address(int param){ int local = param; return &local;tx0 reports: the address of the local variable local is returned} char *name(void){ char buf[16]; buf[0] = 0; return buf;tx0 reports: the address of the local variable buf is returned} int *field(void){ struct point p = { 1, 2 }; return &p.y;tx0 reports: the address of the local variable p is returned} char *element(int i){ char text[8]; return &text[i];tx0 reports: the address of the local variable text is returned} int *fine(int *out, struct point *q){ static int kept; int *p = out; char *s = "text"; if (q) return &q->x; if (s[0]) return &counter; if (out) return p; return &kept;} int *param(int x){ return &x;} Turn it on, off or suppress it
The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:
[rules]
"tx0/c:return-local-address" = "off"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:return-local-address] reason="..."tx0 explain tx0/c:return-local-address shows the same in the terminal. Found a false positive? Report it.