Reputation: 195
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;
}
Upvotes: 0
Views: 87
Reputation: 409136
You are probably running into the reason gets
have 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 gets
will write out of bounds of the array and you will have undefined behavior.
Instead use fgets
to read lines in a safe way.
And regarding that return
from the main
function. 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 atoi
function 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 return 0
. A safer function which will help you detect errors is the strtol
function.
Upvotes: 1