gets() problems

Go To Last Post
6 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0
int main(void)
{    
    // Program initalization
    Initialization();
	
	fdevopen(Usart_Tx,Usart_Rx,0);

	printf("Hello, world!\n");
	
	char *string;

	for (;;) {
		gets (string);
		if (strcmp(string, "on") == 0) {
			sbi(DDRB, 7);
			sbi(PORTB, 7);
		}
		if (strcmp(string, "off") == 0) {
			cbi(DDRB, 7);
			cbi(PORTB, 7);
		}
	}
	
	return 0;
}

It seems to get past gets() but it doesn't toggle the LED when I type on or off and hit enter in the terminal. Any ideas?

Math is cool.
jevinskie.com

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0
   char *string; 
   for (;;) { 
      gets (string); 

You haven't initialized "string", so it points who-knows-where. If it points
to non-existent memory, which seems not unlikely, the gets()-ed string
will vanish. It's likely to cause trouble in any case.

Try:

char string[7+1];

or something.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

No fair. This was a general c question, not gcc specific, it should have been moved to the avr forum.

Imagecraft compiler user

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Actually the code in the original post had fdevopen() and the (deprecated) cbi and sbi macros, which all of the above are specific to GCC. So, it's marginal at best, but it can be allowed. :wink:

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Changing "char *string;" to "char string[8]" didn't work. Adding a \n to the end of the on and off test strings didn't help. string seems to be getting my input because it gets returned to my terminal from the printf. It seems that strcmp is not working right. This is for a butterfly if anyone wants to test it with their own hardware. I have the source and elf and hex files in the zip. Any help?

int main(void)
{    
    // Program initalization
    Initialization();
	
	fdevopen(Usart_Tx,Usart_Rx,0);

	char string[8];
	
	printf("Hello, world!\n");
	
	for (;;) {
		gets (string);
		printf(string);
		if (strcmp(string, "on") == 0) {
			DDRE= (1 << 6);
			PORTE = (1 << 6);
		}
		if (strcmp(string, "off") == 0) {
			DDRE= (1 << 6);
			PORTE = (0 << 6);
		}
	}
	
	return 0;
}

Math is cool.
jevinskie.com

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

strcmp() is known to work correctly. See the `intro' article, please
don't suspect bugs when you didn't investigate.

Did you remember that gets() always returns full lines? Maybe you'd
try strncmp() to make sure only 2 or 3 chars are compared?

Jörg Wunsch

Please don't send me PMs, use email if you want to approach me personally.