[analyzer] Explicit Return and __attribute__((cleanup(..)))
- Dominant language
- LLVM
- Stars
- 40.5k
- Forks
- 18.7k
- PR merge metrics
- PR metrics pending
Description
Uncommenting the explicit return in `process_data` will trigger the following:
```Bash
peng@hackerlife2:~/Desktop$ /home/peng/Downloads/LLVM-21.1.2-Linux-X64/bin/scan-build /home/peng/Downloads/LLVM-21.1.2-Linux-X64/bin/clang test.c
scan-build: Using '/home/peng/Downloads/LLVM-21.1.2-Linux-X64/bin/clang-21' for static analysis
test.c:30:5: warning: Potential leak of memory pointed to by 'data' [unix.Malloc]
30 | return;
| ^~~~~~
1 warning generated.
scan-build: Analysis run complete.
scan-build: 1 bug found.
scan-build: Run 'scan-view /tmp/scan-build-2025-09-24-215520-185566-1' to examine bug reports.
```
```C
#include
#include
#include
// This could be unix.Malloc or any other allocation function
void* my_malloc(size_t size) {
return malloc(size);
}
// The cleanup function.
// IMPORTANT: It takes a pointer to the variable, so char** for a char* variable.
void free_pointer(char **p) {
printf("Cleanup function called for address: %p\n", (void*)*p);
free(*p); // Dereference to get the actual pointer and free it.
}
void process_data() {
// The magic happens here. The variable 'data' is tied to the 'free_pointer' function.
__attribute__((cleanup(free_pointer))) char *data = my_malloc(100);
if (!data) {
perror("Allocation failed");
return;
}
strcpy(data, "Hello, Clang Static Analyzer!");
printf("Data processed: %s\n", data);
// Uncommenting the next line will trigger LEAK WARNING
// return;
// No need to call free(data) here.
// The cleanup function is called automatically when process_data() returns.
}
int main() {
process_data();
printf("Back in main. Memory should be freed.\n");
return 0;
}
```
Contributor guide
Research direction
Reproduce the warning with the provided test.c program using scan-build and clang, comparing the commented and uncommented return paths. Trace how the analyzer handles __attribute__((cleanup(free_pointer))) during an explicit return; done means the valid cleanup path is not reported as a leak while genuine leaks remain diagnosable.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- c
- Domain
- compilers, devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100