Saturday, May 27, 2017

Pointer problems (check your warnings!)

I was working on a Tic Tac Toe console game in C++ with someone I met online.

(We finished it Thursday. : ) Here's the github repo. My partner tried to incorporate AI, but it was too hard for him. Nonetheless, we both enjoyed working together to make it, even if Tic Tac Toe is a small game.)

Anyways, at one point, when I made a Board object in a Board.h header, I originally wrote it like this:


On building, my Code Blocks compiler gave this warning:


I didn't think much of it (I didn't even read it I think lol.). I gave my Board.h to my partner. He started coding in a gui, but at one point, he got an error like this (which I didn't get interestingly):


He was running on Linux, me on Windows, so at first we were stumped. He thought it was just an OS error, until I looked back at the warning. I googled stuff, found this.

Basically, as shown in the first picture of this post, I returned the address of a local array, which would technically be gone after the function call was over, and the address would be pointing to anywhere, leading to undefined behavior. I fixed it by dynamically allocating the array (allocating to the heap, as they call it) with 'new', so the array would exist even after the function call was over, just as needed.


Overall, that was quite an experience in the Skype chat figuring that out, wanted to share it here. It was two big messages, code-wise:

1. "warning: address of local variable <board_layout> returned"
2. "Segmentation fault [core dumped]"


What was interesting was that I didn't get the same behavior as my partner did (because of the undefined behavior I wrote about). But it's nice that the experience ended well, was able to figure out what was happening. I'm pretty sure they say stuff like this in the books or internet, but I feel like, with most things, you understand it the most through practice and experience: the "hard" way, haha. Anyways, what I learned was: check your warnings! They're warnings for a reason!

No comments:

Post a Comment