https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84561

            Bug ID: 84561
           Summary: -Wstrinop-truncation with -O2 depends on strncpy's
                    size type
           Product: gcc
           Version: 8.0.1
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: romain.geissler at amadeus dot com
  Target Milestone: ---

Hi,

There is another -Wformat-truncation that I don't understand with -O2. It looks
like I may or may not get the warning if the inlined size type used in strncpy
is 32 bits or 64 bits, and really can't figure out why that even matters wrt
warnings. Reproducer built with -Wall -Wextra -Werror -O2 on x86_64:

<<EOF
typedef unsigned long size_t;

template <size_t N> class String
{
    public:
        String();

        void set(const char* string, size_t len = N)
        {
            if (len > N)
            {
                len = N;
            }

            __builtin_strncpy(_string, string, len);
            _string[len] = 0;
        }

    private:
        char _string[N + 1];
};

class A
{
    public:
        A() {}

        void setStringSize_t(const char* string, size_t len)
        {
            _string.set(string, len);
        }

        void setStringUnsignedInt(const char* string, unsigned int len)
        {
            _string.set(string, len);
        }
    private:
        String<3> _string;
};

class B
{
    public:
        B() {}

        A& getA()
        {   
            return _a;
        }

    private:
        A _a;
};

void f(A& a)
{   
    a.setStringUnsignedInt("123", 3); //No warning here.
    a.setStringSize_t("123", 3); //No warning here.
}

void f(B& b)
{
    b.getA().setStringUnsignedInt("123", 3); // Unexpected warning here.
    b.getA().setStringSize_t("123", 3); // No warning here.
}
EOF

I am getting this error/warning:

error: ‘char* __builtin_strncpy(char*, const char*, long unsigned int)’ output
truncated before terminating nul copying 3 bytes from a string of the same
length [-Werror=stringop-truncation]
             __builtin_strncpy(_string, string, len);
             ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~

As you can see, using either "size_t" or "unsigned int" for parameter "len"
seems to influence the gcc warning, despite everything is fully inlined. Is
this expected ?

Cheers,
Romain

Reply via email to