0

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;

}
5
  • 2
    Don't use gets. And why are you returning 8585? Try returning 0 Commented Aug 22, 2016 at 1:14
  • Never thought that it would make any difference just return any number will do. Commented Aug 22, 2016 at 1:46
  • 1
    Mmh...where do you run the program you have compiled with gcc-avr? On your PC or on the microcontroller? Commented Aug 22, 2016 at 1:47
  • @AllanMayers What are you typing in as input? Is the length greater than 4 characters? Commented Aug 22, 2016 at 1:55
  • I am learning c to use it with micro controllers so I wanted to get familiar with avr gcc from the start . I thought it would compile a console application on my laptop with no problems. Commented Aug 22, 2016 at 2:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok and that strtol function is it used the same way as atoi?
can you give me an example?
@AllanMayers Follow the link, it leads to a reference which have an example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.