c++static-analysisfilehandlecppcheckfile-pointer

Resource leak or false positive


I have a code like this:

std::string getInfo(FILE *fp)
{
    char buffer[30];
    if (fread(buffer, 19, 1, fp) == 1)
        buffer[19] = '\0';
    else
        buffer[0] = '\0';

    return buffer;
}

I'm using cppcheck for static analysis and it spits a warning:

error: Resource leak: fp [resourceLeak]
 return buffer;
 ^

The way I see it, since the return is by value, the data will be copied from "buffer" into std::string's storage, so there's no leak there.

Does this pose some real problem or is it a false positive?


Solution

  • error: Resource leak: fp [resourceLeak]

    You are not leaking any resource from this function. So, if you're only analyzing this function, this is a bug in your cppcheck. However, as @Taekahn points out - maybe the leak is elsewhere in your program.

    Also, since you're returning std::string, you can use a constructor taking a pointer and a count, and not bother with the '\0' in the buffer:

    std::string getInfo(FILE *fp)
    {
        static constexpr const std::size_t info_length { 19 };
        char buffer[info_length];
        if (fread(buffer, info_length, 1, fp) == 1)
            return {buffer, info_length};
        else
            return {};
    }
    

    If you're using C++23, you might consider returning an std::expected instead of the empty string, e.g. something like:

    std::expected<std::string, errc> getInfo(FILE *fp)
    {
        static constexpr const std::size_t info_length { 19 };
        char buffer[info_length];
        if (fread(buffer, info_length, 1, fp) == 1)
            return std::string{buffer, info_length};
        else
            return std::unexpected{errno};
    }