val ceases to exist before the reference ceases to exist, beacuse it's declared after. So after val is destroyed, the reference is invalid. Declare val earlier. Your code would be very nutty in C too.
I think I disagree with the "your code would be nutty in C" comment. Since C requires all variables to be declared at the top of the scope, and the order of declaration doesn't matter for purposes of allocation, there's no reason to worry about the ordering in this case.
(C does not require all variables to be declared at the top of the scope.) Even if you're using a version of C that does, the order of variables implies something about their lifetimes and your code could make somebody refactoring more likely to believe they can lift the pointer out to the containing scope, or put the int in a smaller scope.