Getting valid input from Ultrasonic range finder
It is likely related to the overall system latency.

The problem is that on a raspberry, or similar linux system (and also applies to platform with an OS), you have a kernel that schedule the tasks (all the other programs running).

While your program may seem to execute continuously on your while (1), the system actually needs to execute other tasks, and can at any moment hang your program.

User-space programs have usually the lowest priority, unless otherwise specified.

What happens, is that sometimes, your program is not executed quickly enough as the system is busy handling other things, and thus time goes by between the time the pin is actually set to 1 and the program will check on it.

There are some way to bypass this issue, but it requires kernel level driver that can control and read the pins with lower latency but is fairly (very) complex to do to some non-kernel driver programmer.

To mitigate the problem, you can try to run the program with a higher execution priority. This will probably help, but may not totally solve the issue.

You can also add a software filtering to ignore those mistaken issues.

Another option, perhaps the best, if your raspberry has several CPU Core, would be to reserve a core for your program alone, so it wouldn't be interrupted

Overall, the best solution would be to use an Arduino like device to control the sensor, and then communicate to the raspberry through SPI or I2C. As the Arduino doesn't have a kernel to or the need to run over tasks, you will have much more accurate measurements on the timings.