Skip to content

[analyzer] Explicit Return and __attribute__((cleanup(..))) #160527

@PengZheng

Description

@PengZheng

Uncommenting the explicit return in process_data will trigger the following:

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.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 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;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:static analyzerenhancementImproving things as opposed to bug fixing, e.g. new or missing feature

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions