|
|
View previous topic :: View next topic |
Author |
Message |
umka
Joined: 28 Aug 2007 Posts: 99 Location: New Zealand
|
Problem with function " gets " |
Posted: Sun Mar 30, 2008 8:03 pm |
|
|
Here is my code. It doesnt seem to not want to come out of the gets routine because if i run the code the string "password" is outputted to the CCS serial monitor window so then i isend mike from the ascii line and then have to stop running the program coz nothing happens. the strings "word" and "password" are both set to "mike" but the compair (sttricmp) is not happening.
if i comment out the gets(word) and use strcpy(word,"mike") the program run fine in a continous loop outputting "pass"
Code: | #include <16F877a.H>
#device icd = true
#fuses XT, NOWDT, NOPROTECT, BROWNOUT, PUT, NOLVP
#use delay(clock = 4000000)
#use rs232(baud=9600, xmit=PIN_c6, rcv=PIN_c7, BITS =8, PARITY=n, stop=1)
#include <string.h>
char word[4];
char password[4];
void main()
{
strcpy(word,"");
strcpy(password,"mike");
while(true)
{
output_high(pin_d2);
delay_ms(500);
printf("Password: ");
delay_ms(50);
gets(word);
// strcpy(word,"mike");
if(stricmp(password,word))
{printf("Pass");}
else
{printf("Fail");}
output_low(pin_d2);
delay_ms(500);
}
} |
|
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Sun Mar 30, 2008 11:37 pm |
|
|
1. Your array is too small to hold a 4-character string.
The array size must be at least one element larger than the maximum
expected string size. That's because a string always has a 0x00 byte
at the end. This byte is inserted by gets().
2. Your code is unsafe. If the user types in more than the expected
number of characters, you will overwrite RAM beyond the limits of
your array and destroy other variables, possibly causing your
program to crash. It's much better to use the get_string() function.
See this thread for examples:
http://www.ccsinfo.com/forum/viewtopic.php?t=17563
3. Always put ERRORS in your #use rs232() statement, to prevent
possible lockups, when you use large delay_ms() values prior to
reading the UART. Use ERRORS in all your programs. |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|