Reputation: 125
I am writing the following code and I am getting Stack around variable is corrupted
error. I have checked similar posts but couldn't relate the problems. I am also rather new to C++. Here is my code.
///CLASS DEFINITION
class Trellis{
private:
int m;
int Nstates;
int StateTransition[];
public:
Trellis();
Trellis(int M);
};
Here is the definition of methods
Trellis::Trellis(int M){
m = M;
Nstates = pow(2, M - 1);
for (int i = 0; i < Nstates; i++){
StateTransition[i] = i;
}
}
int main() {
Trellis Tu = Trellis(3);
return 0; }
The error I get is Run-Time Check Failure #2-Stack around variuble 'Tu' was corrupted;
Upvotes: 0
Views: 462
Reputation: 43662
Flexible array members were a C99 feature which allowed you to do something like
struct header {
size_t len;
unsigned char data[];
};
and, provided that you had a proper memory layout, you could access and write to the data
array.
In your case you're not providing any memory for your StateTransition
variable and thus overwriting some other stack data.
You had better doing something like
class Trellis
{
private:
int m;
int Nstates;
int *StateTransition; // Pointer
public:
Trellis();
Trellis(int M);
~Trellis();
};
Trellis::Trellis() : StateTransition(0) {
}
Trellis::Trellis(int M) : StateTransition(0)
{
m = M;
Nstates = pow(2, M - 1);
StateTransition = new int[Nstates]; // Allocate memory
for (int i = 0; i < Nstates; i++)
{
StateTransition[i] = i;
}
}
Trellis::~Trellis() {
if(StateTransition != 0)
delete[] StateTransition; // Always be a good citizen
}
And as for the rule of three, you might also want to write a copy constructor.
Upvotes: 0
Reputation: 27567
You're not allocating any memory for StateTransition
, you want something like:
StateTransition = new int[Nstates];
before your for
loop in the ctor.
Upvotes: 4