I'm new to C++, and I'm writing a simple blockchain program as a sort of exercise. When I run the below code, I seem to get an error of sorts:
Process returned -1073741819 (0xC0000005)
The code is below:
#include <iostream>
#include <time.h>
#include <string>
using namespace std;
class Block
{
int data, previous_hash;
public:
string timestamp;
Block(string a, int b, int c)
{
timestamp = a;
data = b;
previous_hash = c;
};
};
string getTime()
{
time_t now = time(NULL);
struct tm tstruct;
char buf[40];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%X", &tstruct);
return buf; //Simple code to return current time
}
class BlockChain
{
public:
Block chain[];
BlockChain()
{
chain[0]=createGenesisBlock();
}
Block createGenesisBlock()
{
return Block(getTime(), 10, 0);
}
};
int main()
{
BlockChain myChain;
cout << "current time is " << getTime();
cout << myChain.chain[0].timestamp; //Is this correct?
}
I included a line in main() to access the string timestamp
in my object mychain
. I suspect this may be the problem, but i'm not sure how else I can access timestamp when its called over both Blockchain
and Block
classes.
Currently, BlockChain::chain
is an array with unknown size. But when you access chain[0]
in BlockChain
's constructor, you're assuming that chain
points to valid memory, which it doesn't because you never initialize it. That's why you're getting a crash due to a bad memory access. I would suggest the use of std::vector<Block>
instead of Block[]
, which you can resize as needed:
class BlockChain {
public:
std::vector<Block> chain;
BlockChain() {
// initialize and append a new block to chain
chain.emplace_back(createGenesisBlock());
}
User contributions licensed under CC BY-SA 3.0