I'm learning C. So I wrote this distance timer program. It runs well with gnu-gcc compiler. But but with gnu-gcc for avr it does compile but when I run it I get only a cmd session that does nothing except disappearing once I press any button. I want to know why.
I am using code blocks and here is my code
#include<stdio.h>
#include<stdlib.h>
#define speedpersecond 5
int main()
{
char time [5];
double distance;
printf("Please enter time in seconds");
gets(time);
distance = atoi(time) * speedpersecond;
printf("Distance is %g ", distance);
return 8585;
}
You are probably running into the reason
getshave been deprecated since the C99 standard, and removed completely in the C11 standard: Buffer overflows are way to easy.If you give more than four characters as input then
getswill write out of bounds of the array and you will have undefined behavior.Instead use
fgetsto read lines in a safe way.And regarding that
returnfrom themainfunction. Many systems (including all POSIX systems, like macOS and Linux) uses eight bits for the return value. Also, anything but zero is considered to be a failure by shells and calling environments.You should also know that the
atoifunction have no major error checking. It's impossible to know if the string you pass contains e.g."0"or don't have any digits at all. In both cases it will return0. A safer function which will help you detect errors is thestrtolfunction.