I'm having trouble with adding structures to array in cpp. I've came up with this method which works great on ints but when i want to do the same thing on structures im getting error after adding 3 or more. I debugged it a little bit and it seems that delete[] is causing error message "Segmentation fault (core dumped)". I cant use vectors or list from stl so dont suggest that Here's some code:
struct sth
{
unsigned int id;
std::string name;
};
unsigned int id_counter = 0;
unsigned int counter_int = 0;
sth *array = new sth[0];
void print_array()
{
for (int i = 0; i < counter_int; ++i)
{
std::cout << array[i].id << ' ' << array[i].name << " -- ";
}
std::cout << '\n';
}
void add_sth(sth value)
{
sth *newArr = new sth[counter_int + 1];
memcpy(newArr, array, counter_int * sizeof(sth));
delete[] array;
array = newArr;
array[counter_int] = value;
++id_counter;
++counter_int;
}
int main(int argc, char const *argv[])
{
sth e1 = {1, "abc1"};
sth e2 = {2, "abc2"};
add_sth(e1);
add_sth(e2);
add_sth(e2);
print_array();
}
The problem is probably trying to copy an std::string
with memcpy.
std::string
is not a POD (Plain Old Data) object, and some compilers and
certainly static code analyzers e.g. SonarQube or Klocwork will alert you that
what you are doing is wrong.
To accomplish a copy correctly you should define an assignment operator and
copy the items one by one, or just use a dynamic container e.g. std::vector