OK (not really). You insert battery into errr .. standby battery socket for the first time. You power you board, maybe run into main() and stop there. Startup routine didn't clear your custom memory area, so NV RAM doesn't contain zeros but something. You have declared flag variable like this
__declspec(..) int flag; // allocated not in .bss, .sbss, .data, or .sdata memory sections, so startup doesn't clear it
So you didn't writte into flag after last Vstb power on. What does flag contain? Most likely it won't contain all zeros or all ones, most likely ir will be something like 0x547ABf0, random bits pattern. And you define some less random pattern, say 0xaa55aa55, 0xa55a5aa5, 0xC0DEBEEF, etc. It is not very likely to find such pattern in RAM after power on. So you read flag, compare it to 0xaa55aa55 or other not very expected "random" power on values and decide to think RAM was powerd off, or not to think that RAM was powered off. etc
Regarding risk of flipping bits. I meant that if you power off RAM for too short, pattern in RAM may or may not revert to "random" state. In case flag is the same like you wrote it, other locations in RAM may already have some bits flipped.