Reputation: 1
I have this piece of code (something I threw together trying to isolate a weird error in a chess program I'm trying to write):
#include <vector>
#include <iostream>
class piece{
public:
piece() : COLOUR('C'){}
const char COLOUR;
};
std::vector<piece*> makeEmptyLine(){
std::vector<piece*> emptyLine;
piece null;
emptyLine.push_back(&null);
return emptyLine;
}
int main(){
std::vector<piece*> emptyLine = makeEmptyLine();
std::cout << (*emptyLine[0]).COLOUR;
std::cout << (*emptyLine[0]).COLOUR;
std::cout << (*emptyLine[0]).COLOUR;
return 0;
}
And the output is C\367\367
The first std::cout << (*emptyLine[0]).COLOUR;
always prints "C" (the expected result). But when it's used again, it outputs that backslash and three digits which change depending on how many times I use cout in the program.
Upvotes: 0
Views: 44
Reputation: 5186
You have an undefined behaviour because you use the address of a local variable null
which is destroyed once your function makeEmptyLine()
returns.
Does your compiler complain when you try to compile it with the highest warning level?
Upvotes: 1