possible problems after resizing dynamic array - c++

Got little problem here.
I created dynamic array:
m_elements = new struct element*[m_number_of_elements];
for(int i = 0; i < m_number_of_elements; i++)
{
m_elements[i] = new struct element[m_element_size];
}
then I tried to resize existing array:
m_elements[m_number_of_elements] = create_more_elements();
m_number_of_elements++;
create_more_elements() is a function:
struct index* create_more_elements()
{
struct element* tmp = new struct element[m_number_of_elements]
return tmp;
}
In general, this piece of code works, but sometimes I get segfaults in different places.
Are segfaults connected with resizing?
Any thoughts?

You should use std::vector for it, then you can with new allocate memory for new struct and push her pointer to vector, if you deleting you should delete on pointer.

Try this:
std::vector<element> m_elements;
m_elements.resize(m_number_of_elements);
Don't go the route of manually managing an array unless absolutely necessary - std::vector will do a far better job, is better tested, proven, standardized and understood by legions of C++ programmers. See my code example - not even a single new or delete statement, yet this code also contains all required memory management.
P.S.: Since this question is tagged as C++, you don't have to write struct element whereever you use it as a type, just element will suffice. This suggests you are coming from C, so my advice: learn about the STL before you continue what you're doing, a single hour spent learning how to use the standard container classes can save you many days of manual tweaking, debugging and bug-fixing. Especially since once you've learnt one, you already know like 80% about all the others. :)

m_elements[i] = new struct element[m_element_size];
This creates an array of element of size m_element_size
To dynamically create a struct, just use new struct element or new element.
If don't have to initialize values in your array, you may even be better not storing pointers but actual objects in your array:
m_elements = new element[m_number_of_elements];
To "resize" an array, you actually have to allocate a new bigger array, copy the content of current array in the new one, and delete the old array.
// Allocate new array
element* newArray = new element[m_number_of_elements + 1];
// Copy old array content into new one
memcpy(newArray, m_elements, m_number_of_elements * sizeof(element)];
// Delete old array
delete[] m_elements;
// Assign new array
m_elements = newArray;
// Keep new size
m_number_of_elements += 1;
But you should definitely use std::vector which is simpler and smarter than that:
std::vector<element> elements;
// Add an element
Element element;
...
elements.push_back(element);

It is a wonder that you code even works. Basically what you are doing is overwriting memory after your initially allocated array. In C++ you can't resize the array, you can only delete it and new up a new one.
element** tmp = new element*[m_number_of_elements];
for(int i = 0; i < m_number_of_elements; i++)
{
tmp[i] = m_elements[i]
}
delete m_elements;
m_elements = tmp;
m_elements[m_number_of_elements] = create_more_elements();
m_number_of_elements++;
But, that is really crufty. As Svisstack points out, you should use std::vector or any other suitable standard container.
std::vector<element*> m_elements;
// ...
m_elements.push_back(create_more_elements());

Related

C++ dynamic array of pointer to another class

Hello i'm trying to create a dynamic array of pointer to an object Student from Gradesclass but i can't figure out how to declare it in the header
that's the header:
class Grades
{
private:
Student** array;
int _numofStud;
public:
Grades();
Grades(const Grades& other);
~Grades();
and the grades constructor (i'm not sure it's right)
Grades::Grades()
{
this->array = new Student * [2];
for (int i = 0; i < 2; ++i)
{
this->array[i] = NULL;
}
this->array[0]= new Student("auto1", "12345");
this->array[1]= new Student("auto2", "67890");
this->_numofStud = 2;
}
The probleme is that before it even enter to the constructor, it creating me an array of Size 5 in Grades because i have 5 elements in the Student constructor
Student::Student(const char* name, char* id)
{
this->_numofgrade = 0;
this->setName(name);
this->setId(id);
this->_grades = NULL;
this->_average = 0;
}
And i can't add or modify this size
I want to put a default size of Grades to an array of 2 pointers to student object that i'll define as default then i'll have an other methods that add new Students by creating them and adding their pointers to the array
Th problem is i can't change the size of array and i don't understand why
I hope i was clear in my explanation thanks for your help
Edit:
that's the debuger and you can see when it's creating a new object Grades g1
it's creating an array of 5 instead off two
fill the 2 first as i asked for
and the 3 left i have no idea why they have been created and whats inside them
OK, so to be clear, in any actual programs you should use std::vector or other containers, they have a lot of features I ignored here (being templates, supporting move semantics, not requiring a default constructor, etc.), a lot of saftey (what if a constructor throws an exception? What if I do array.add(array[0])?), while still being pretty well optimised for general purpose usage.
And you should also really look at std::unique_ptr, manual new, delete, is generally asking for leaks and other mistakes, in C++ a manual "free" or "delete" of any resource is almost never needed.
Also note in C++ size_t is often used for sizes/lengths of objects and containers.
So the basic idea of a dynamic array is it changes it's size based on current requirements, so Grades() can just start off empty for example.
Grades::Grades()
: array(nullptr), _numofStud(0)
{}
Then when adding a new item, a new larger array is made, and all the existing items are copied (roughly what std::vector::push_back(x) does).
void Grades::addStudent(Student *student)
{
// make a larger array
Student **newArray = new Student*[_numofStud + 1];
// copy all the values
for (int i = 0; i < _numofStud; ++i)
newArray[i] = array[i]; // copy existing item
// new item
newArray[_numofStud] = student;
++_numofStud;
// get rid of old array
delete[] array;
// use new array
array = newArray;
}

C++ allocating an array of pointers to struct

I am writing a program which needs to have an array of pointers to a struct SMesh, specifically
SMesh **mesh_arr;
When I work with an instance that has only one pointer in the array, everything is OK. But when I try to work with instance that has got two (or more) of them, Valgrind goes crazy with "Invalid write of size...".
I initialize it like this (with counter being the number of SMeshes that I need pointers to) :
SMesh **mesh_arr = new SMesh*;
for (int i = 0; i < counter; i++) mesh_arr[i] = new SMesh;
And delete it like this :
delete mesh_arr;
Do I delete it the wrong way or have I missed something?
You have to allocate enough elements to have the entire array, not only 1 element.
SMesh **mesh_arr = new SMesh*[counter];
for (int i = 0; i < counter; i++) mesh_arr[i] = new SMesh;
Using new[], you have to use delete[] to delete it.
delete[] mesh_arr;
Also don't forget to delete the individual SMeshs allocated.
You can avoid pointer trouble with a vector. No need to explicitly delete either.
#include <vector>
auto mesharr{std::vector<std::vector<SMesh>>(rows, std::vector<SMesh>(cols))};
You have only allocated one pointer to your structure in your new statement. Try
SMesh ** mesh_arr = new (SMesh*)[counter];

Copy array then delete original

I have an array of a structure (with the parameters of name and number), and the initial array takes in elements from a document that I've made. The initial list size starts at 1000. When the list fills up, I call another method that I'm struggling with. I would like for it to copy the data into a new array that doubled the size, and then delete the old array.
If I name it: array1 and array2, I have my program use array1 throughout. I need help with the pointers that would get array2 to work as array1.
Is there a way to copy the array to a temp array of the same or new size, and then remake the initial array reassigning back to that? For this exercise, I can't use vectors. While I know how to use them, and that they solve this issue while being better, I'm trying to do it with only arrays.
using namespace std;
struct Information {
char functionality;
int SSN;
string name;
};
int numPeople = 1000;
//Gets called if the initial array (whatever size) is filled
void doubleArray(Information *array){
numPeople = numPeople * 2;
//Will now be the doubled array size
Information temp[numPeople]
for(int i = 0; i < numArray; i++){
temp[i].SSN = array[i].SSN;
temp[i].name = array[i].name;
}
//Normally makes it crash
delete[] array;
}
edit: This is what I currently have
void doubleArray(Information *person){
numPeople = numPeople * 2;
Information* temp = new Information[numPeople];
memcpy(temp, person, numPeople);
delete[] person;
person = temp;
}
It gets to numPeople = 1000 (the initial list size) but then crashes shortly after. Is the doubling array correct?
Arrays are fixed size. You cannot change the capacity of the original array.
{Use std::vector}
You can have a pointer to an array. And use the same pointer. When the array is full, you can allocate another array, copy old array items to new array, delete the old array and assign your array pointer to the new array.
{Did I mention std::vector?}
By the way, there is a data structure that performs resizing as necessary. If I recall correctly, it is std::vector. Try it out. :-)
Assuming you are using std::array (which you should be), then copying the array is very easy.
std::array<myStruct, 1000> array1{};
std::array<myStruct, 2000> array2{};
// codes...
std::copy(array1.begin(), array1.end(), array2.begin())
However, this is a specific scenario in which you only use these two arrays. It will not dynamically double the size of the array as you simply cannot do this dynamically with stack-based arrays, just like c arrays[].
What you can, and should, be using is std::vector<myStruct>. This will dynamically grow as you need it. Until you provide us with code and a more specific issue, this is the best advice that I can offer with the information provided.
If you aren't allowed to use std::vector, as one of your comments stated, then you'll want to look at dynamic allocation.
size_t sz = [whatever];
// Dynamically allocate an array of size sz.
T* T_array = new T[sz];
// Do whatever...
delete[] T_array; // new[] needs to be paired with delete[].
T_array = nullptr; // Not strictly necessary, but a good idea if you have more code after.
As the size doesn't need to be constant for a dynamic array, this will allow you to allocate memory as necessary. You can then use std::copy() to copy data from one array to the other, as Goodies mentioned.
[For more information on dynamic allocation, see here.]

How does dynamic space allocation actually work in this algorithm?

I have made for school purposes my own take on a dynamically allocated array using templates.
While what I'm about to ask works, I don't know how and why and I've reached the point where I need to know.
template <typename TElement>
DynamicArray<TElement>::ensureCapacity () {
if (capacity >= elemNumb) {
return; //we have space to store the values
}
//we need to allocate more space for the values
TElement *auxArray = myArray;
//create space to hold more numbers
capacity = capacity * 2;
myArray = new TElement[capacity];
//copy the values
for (int i = 0; i < size; i++) {
myArray[i] = auxArray[i];
}
//release the memory
delete[] auxArray;
}
I need to know: TElement *auxArray = myArray; How does this work ? is it using pointers, are elements copied one by one ? I need to understand how it works so that I can figure out the complexity of my algorithm. I don't mind if some one tells me the complexity but the real answer I'm looking for is how does that work ?
Also myArray = new TElement[capacity]; I do this before deleting the old myArray does this delete the old one ? or is it still floating somewhere in memory in one form or another ?
This
TElement *auxArray = myArray;
just means that auxArray points to whatever myArray is pointing to. There is no copying of anything else, it is just a pointer copy.
This
myArray = new TElement[capacity];
means that myArray now points to a new, dynamically allocated TElement array. The expression doesn't delete anything. But auxArray is pointing to what myArray was pointing before this assignment, so when you delete auxArray, you release the resources originally pointed to by myArray.

creating an array of object pointers C++

I want to create an array that holds pointers to many object, but I don't know in advance the number of objects I'll hold, which means that I need to dynamically allocate memory for the array. I have thought of the next code:
ants = new *Ant[num_ants];
for (i=1;i<num_ants+1;i++)
{
ants[i-1] = new Ant();
}
where ants is defined as Ant **ants; and Ant is a class.
Will it work?
Will it work?
Yes.
However, if possible, you should use a vector:
#include <vector>
std::vector<Ant*> ants;
for (int i = 0; i < num_ants; ++i) {
ants.push_back(new Ant());
}
If you have to use a dynamically allocated array then I would prefer this syntax:
typedef Ant* AntPtr;
AntPtr * ants = new AntPtr[num_ants];
for (int i = 0; i < num_ants; ++i) {
ants[i] = new Ant();
}
But forget all that. The code still isn't any good since it requires manual memory management. To fix that you could to change your code to:
std::vector<std::unique_ptr<Ant>> ants;
for (auto i = 0; i != num_ants; ++i) {
ants.push_back(std::make_unique<Ant>());
}
And best of all would be simply this:
std::vector<Ant> ants(num_ants);
std::vector<Ant> ants(num_ants);
ants.resize(new_num_ants);
Yes that's the general idea. However, there are alternatives. Are you sure you need an array of pointers? An array of objects of class Ant may be sufficient. The you would only need to allocate the array:
Ant *ants = new Ant[num_ants];
In general, you should prefer using std::vector to using an array. A vector can grow as needed, and it will handle the memory management for you.
In the code you have posted, you would have to delete each element of ants in a loop, and then delete the array itself, delete [] ant. Keep in mind the difference between delete and delete [].
One more point, since array indices in C++ are 0-based, the following convention is used to iterate over the elements:
for (i=0; i<num_ants; i++)
{
ants[i] = new Ant();
}
This makes code much more readable.
Do you really need to hold pointers to the items? If you can use objects by value, a far simpler approach is to use a vector: std::vector<Ant> ants(num_ants);. Then not only do you not have to write looping, but you don't have to worry about memory leaks from raw pointers and other object management items.
If you need object pointers to say satisfy an API you can still use vector for the outer container and allocate the objects manually.
struct CreateAnt
{
Ant* operator()() const { return new Ant; }
};
std::vector<Ant*> ants(num_ants); // Create vector with null pointers.
std::generate(ants.begin(), ants.end(), CreateAnt());
std::vector<Ant*> ants( num_ants );
for ( int i = 0; i != num_ants; ++ i ) {
ants[i] = new Ant;
}
Or if you don't know how many in advance:
std::vector<Ant*> ants;
while ( moreAntsNeeded() ) {
ants.push_back( new Ant );
}
On the other hand, I think you need to ask yourself whether
Ant is an entity type or a value. If it's a value, you'll
probably want to skip the pointers and the dynamic allocation;
if it's an entity type, you'll have to consider the lifetime of
the object, and when and where it will be deleted.