To make this as quick and concise as possible, this is my code:
char* aiMove = getAIMove();
cout << aiMove;
cout << "\n" << numMoves << ": " << aiMove << "\n\n";
return aiMove;
And this is my output:
a0 a1
0: �����������������������7
So, the first line calls getAIMove() and assigns the return value (char*) to aiMove.
The second line prints aiMove (a0 a1).
The third line takes numMoves and aiMove into cout and prints it, but it’s printing some strange value instead.
The 4th line returns aiMove, which I’ve inspected to be the strange value printed.
Why has the value of aiMove changed? It seems to only happen when I pass an integer value into cout (in this case, numMoves).
Please help!
Thanks,
Patrick 🙂
edit: another thing that I forgot to mention is that this strange behaviour only happens when this block of code gets executed for the first time, every following time it gets run during the program it prints fine.
This is a clear indication that
getAIMovereturned a pointer to memory that the system felt free to reuse. A subsequent allocation, from either the stack or the heap, overwrote the returned pointer.There are lots of ways this can happen, this is probably the most common:
Oops. This code returns a pointer to a buffer that ceases to exist as soon as it returns. A typical fix for this issue would be
return strdup(buf);. Just remember that the caller of the function needs to free the string when it’s done with it.Here’s another way:
The fix for this is
std::string aiMove = GetAIMove. NowaiMovekeeps the string in scope.But the best fix is to use a string class specifically designed to hold strings all the way through:
Note that while this code appears to involve a lot of copying, in practice, modern compilers will make it efficient. So don’t feel bad about keeping your code simple, logical, and easy to understand and maintain.