The answer depends on what rule set you're playing under. Since you didn't mention that detail, I'll answer in the context of World Pool-Billiard Association (WPA) rules. The WPA is the international governing body for pool (pocket billiards).
When the cue ball doesn't hit an object ball (regardless of whether or not it hits a rail), it results in a "standard foul".
When a player commits a "standard foul", play passes to the opponent. The opponent begins with the cue ball in the hand from anywhere on the table.
Whether or not the shooting player declared a safety, the outcome is the same. For a safety shot to be "legal", it must be foul-free.
The three points made above also apply if the player is shooting for the 8 ball. There is no further penalty if this happens when shooting for the 8 ball.
Here are the relevant sections from the WPA rules (any emphasis is ours).
Section 3.9 of the rules of 8 ball tell us that "no rail after contact" is a "standard foul".
3.9 Standard Fouls (8 Ball)
If the shooter commits a foul, play passes to his opponent. The cue ball is in hand, and the incoming player may place it anywhere on the playing surface. (See 1.5 Cue Ball in Hand.)
The following are standard fouls at eight ball:
- (6.3) No Rail after Contact
Section 6.3 expands the detail on the "no rail after contact" standard foul. Again, this tells us that failure to contact a rail is indeed a foul, and by extension, that "the cue ball must contact an object ball". You can see here that it doesn't matter if the cue ball contacts a cushion or not, since the shot didn't meet the "must contact an object ball" prerequisite. The final part confirms (again) that the scenario results in a "standard foul".
6.3 No Rail after Contact (8 Ball)
If no ball is pocketed on a shot, the cue ball must contact an object ball, and after that, contact at least one ball (cue ball or any object ball) must be driven to a rail, or the shot is a foul. (See 8.4 Driven to a Rail.)
Again, there's no need to point to any of the rules related to declaring a "safety shot", since it has no effect on the answer to your question.
Finally, please note that this answer is based on WPA rules. If you play under any other set of rules (such as APA rules), then you must consult those specific rules. They will likely differ slightly from what is here. The APA, for example, has a several technical documents for clarifications dedicated to defensive play and safety shots.