Reputation: 1116
I have a class called Item that stores an array of a size known at compile time:
class Item
{
int *data;
public:
Item(int array[], int length)
{
std::copy(array, array + length, data); // Line A
}
};
In my example the size equals to 1, but for my project I need greater values as well. Here is a class Box that stores two Items. I don't want to have two arguments in the constructor, so I pass an array of size 2 (since the class can only store 2 Items and each of them stores an array of length 1).
class Box
{
Item *item1;
Item *item2;
public:
Box(int (&array)[2])
{
item1 = new Item(array, 1);
item2 = new Item(array + 1, 1);
}
~Box()
{
delete item1;
delete item2;
}
};
And this is how I create a pointer to a Box object:
int main()
{
int tab[] = {8, 9};
Box *box = new Box(tab);
delete box;
return 0;
}
After running the above piece of code, I got the following error:
Segmentation fault (core dumped).
I debugged it and it turned out that the line A is causing the problem. I also create the Item class in my main function and it doesn't give me any errors.
It seems to me that I'm trying to access some memory outside of my table, but this can't be true - I just want to copy one element of my array. Besides, the c++ compiler wouldn't mind it anyway.
So, what am I doing wrong? How can I fix it?
I'm using the g++ compiler and the -std=c++11 option.
I can use std::array instead, but I'd like to know what mistake am I making just out of curiosity.
Upvotes: 0
Views: 855
Reputation: 409482
The expression new int(length)
only allocates a single int
and initializes it to the value of lenght
.
You need to use square brackets []
for the size: new int[length]
.
Upvotes: 2
Reputation: 304122
Item
isn't quite right. When you have:
std::copy(array, array + length, data); // Line A
You're never actually allocating anything for data
first - so you're writing into whatever garbage happens to be in that pointer when it's initialized. You need to first do something like:
data = new int[length];
std::copy(array, array + length, data);
Although then you have remember to add a destructor, and copy/move assignment. Even better would be to simply use what the standard provides:
using Item = std::vector<int>;
Besides, the c++ compiler wouldn't mind it anyway.
Just because code compiles doesn't mean it works. Compilation catches a lot of bugs for us, but it can't do everything!
Upvotes: 3