I am using a global array (I know they are evil). This is not so much a problem, but I don’t know why it works one way and not the other, as they should be the same. (that and otherwise I need to deallocate memory after in the currently working way).
Anyway, I have this Snake class. I want to make, this being the global array:
Snake snakes[8];
I have several (or will anyway) several classes and function that interact with this. The problem in question occurs with a setter function in the Snake class. It compiles fine, but segfaults. It turned out, this was a null pointer (0x0). Not sure why. The stack trace in this case came from a function call from another file, which includes the snake header and has this:
extern Snake * snakes;
An array’s name is a pointer, so I figured this should work. Oddly enough, it does not. I have no idea why.
But, when I change the declaration from what it was to:
Snake * snakes;
And later allocate it like so:
snakes = new Snake [8];
It works! But, then I need to deallocate something else I didn’t want to, when the number of snakes is constant. (8).
Also, the function call in question accesses the 0th element, where there were 8 elements each time.
Any idea what causes this?
On a side note, are global variables still evil when in a named namespace? (not anonymous). I ask because I am trying to get into the OO habit and logically structure things, which I am certain will pay off compared to my last endeavors, the encapsulation, organization, etc, all make sense. (and maybe in a few years, compile time). Still, having to include a scoped variable in a function call for setting seems… bad. Is that proper or is there a better way? (then global, namespace or otherwise)
EDIT: The error is a segfault, at the line of the member function.
Snake member function:
void setValue(Some value here...) {this-> value = input)
The call from the file that externed the global array:
snakes[0].setValue(some value here...)
An array’s name is not a pointer. In most contexts it decays into a pointer, but when it doesn’t, it doesn’t. So if you have:
in one source file and
in another, you’ll get all kinds of mysterious problems, including crashes. For an array, the extern declaration must declare an array:
Incidentally, I know this because I had exactly the same problem many years ago, and that’s when I figured out how to do this.