I'm getting a segmentation fault, and I'm not sure why. Basically I'm trying to print out a game board where '@' ('iblock' class) is the border, and the inside is just ' ' ('empty' class). I get a segmentation fault after it prints out the top border. For example, i'm trying to get something like this:
Here's my code. I'm inheriting class object in the "iblock" class and "empty" class, and am also using a pure virtual function in "object" class for the function "getType()"
Hi
Inside your initializeBoard function you've got:
1 2
iblock x;
empty j;
These are two local variables, created on the stack, that will expire as soon as you reach the end of the function. Yet you're assigning their addresses to your board array.
A very quick (and very horrible) fix would be to declare these as static:
1 2
static iblock x;
static empty j;
But you should really revisit this whole design if you want to take the code any further, I think.
Your 'board' should be a separate class on its own, and I'd try to move away from arrays and pointers altogether and use std::vector instead - you'll never regret it ;)
Regards, keineahnung
Thanks for the reply keineahnung. I figured my design had some flaw in it because I couldn't really see a way around it.
Just out of curiosity, if the variables expire as soon as the function is over, then how come my program was able to print out at least the first line of "@"? And what exactly does static do (and why would it be a horrible idea?)?
@jkayme
Just out of curiosity, if the variables expire as soon as the function is over, then how come my program was able to print out at least the first line of "@"?
Actually on my system it didn't - it just segfaulted straight away. So I think you could say the results will be undefined, which is never a good sign.
And what exactly does static do (and why would it be a horrible idea?)?
Erm, I don't have a textbook definition to hand (- look to your favourite C++ reference for that ;). But in this example it basically means the variables 'live on' after the function ends, so the addresses you assigned remain valid for the lifetime of the program.
A bad idea because your data should be packaged up inside the private implementation of the relevant class, with access controlled by a public interface. That's the C++ way :)