Can someone explain to me why this piece of code fails:
I get a segmentation fault after writeStoredData() writes 0,1,2,3,4 to the console.
#include <iostream>
//Class storing data
class DataStorage
{
public:
DataStorage()
{
}
~DataStorage()
{
delete x;
}
void storeThis(int* xIn, unsigned sizeIn)
{
x = xIn;
size = sizeIn;
}
void writeStoredData()
{
for (unsigned i=0; i<size; ++i) {
std::cout << x[i] << std::endl;
}
}
bool exist(int value)
{
for (unsigned i=0; i<size; ++i) {
if (x = value) {
return true;
}
}
return true;
}
private:
int *x;
unsigned size;
};
//Stores and writes the stored data
void exercise1()
{
std::cout << "Exercise 1" << std::endl;
int x[5] = {0,1,2,3,4};
DataStorage dataStorage;
dataStorage.storeThis(x,5);
dataStorage.writeStoredData();
}
int main(int argc, char* argv[])
{
exercise1();
return 0;
}
what simple changes could I make to solve this problem?