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

            Bug ID: 108063
           Summary: push_back on std::vector allocates wrong amount of
                    memory
           Product: gcc
           Version: 12.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: jo.rickert at protonmail dot ch
  Target Milestone: ---

Created attachment 54067
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=54067&action=edit
Source Code with a main.cpp and additional .cpp / .h files with all the .o and
.ii Files

When you have two classes with the same name (in different .cpp Files), the two
classes have different size, for instance one with one integer member and the
other with two integer members. Then if you do a push_back of each class on a
vector the second instance does not allocate the right amount of memory and
undefined actions occur.

The system the files are from is a manjaro Linux with a gcc Version 12.2.0

I tried it on a windows 10 with gcc 12.2.0, Fedora 35 with gcc 11.3.1-3 and a
centos7 with gcc 4.8.5 the bug occured on all versions.

The second instance of this pushing on the vector does not even need to be
called only to be compiled.

Setup in the attached code:

File dummy.cpp (code in this file never gets called, but if this file is linked
then the generated source code creates undefined behavior):
contains a class Item with two integer members. It has an unused functions that
creates a std::vector<Item> uses push_back with an Item.

File undefined_behavior.cpp:
Has also a class Item but only with one Integer Member.
Here we also have a function that creates a std::vector<Item> but when we use
push_back here the allocated memory does strange things. If emplace_back is
used instead it throws an allocation error.
This function also prints the content of the vector, to show that it makes no
sense.

File undefined_behavior.h:
contains the declaration of the function in undefined_behavior.cpp

File main.cpp
only includes undefined_behavior.h and calls the function.

The expected output of my program is:
Value of 0 is: 0
Value of 1 is: 1
Value of 2 is: 2
Value of 3 is: 3
Value of 4 is: 4
Value of 5 is: 5
Value of 6 is: 6
Value of 7 is: 7
Value of 8 is: 8
Value of 9 is: 9

Actual output varies from system to system:
Value of 0 is: 0
Value of 1 is: 0
Value of 2 is: 1
Value of 3 is: 0
Value of 4 is: 2
Value of 5 is: 0
Value of 6 is: 3
Value of 7 is: 0
Value of 8 is: 4
Value of 9 is: 0

or:
Value of 0 is: 0
Value of 1 is: 0
Value of 2 is: 1
Value of 3 is: 29499056
Value of 4 is: 2
Value of 5 is: 29499088
Value of 6 is: 3
Value of 7 is: 29499120
Value of 8 is: 4
Value of 9 is: 29499120

When push_back is replaced with emplace_back it most of the time throws
bac_alloc and crashes.

Reply via email to