This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

about scanf retarget in Cortexm3 of SmartFuson of Actel

Hi,

I have one question about Cortexm3 from smartfusion device from actel. Could you pls help me?
I add follwing codes into retarget.c and then add retarget.c into source code group and find :
printf function works.however scanf function doesn't. anybody knows why?

int fputc(int ch, FILE *f) {
return ((int)ITM_SendChar(ch));
}

int fgetc(FILE *f) {
int i=0;
i=ITM_ReceiveChar();
if((-1)!=i)
        return ((int)ITM_SendChar((uint32_t)i));
else
        return (0);
}
  printf("hello world\n\r"); // when executed, string displayed in debug(printf)window
  scanf("%s",str);                // when executed, hard fault occurs

Parents
  • So all do ever do is to get a single string for each input line? Why then don't you use the gets() function, that (in Keils edition) takes a parameter specifying the size of your buffer?

    But the worst problem - str is expected to be a string. But your declaration is a character. Taking the address of the character and send into sprintf() means that sprintf() only have a valid if it is expected to retrieve a zero-length string (i.e. a string only storing the termination character).

    You must definitely need to make:

    enum {
        BUF_SIZE = 64,
    };
    char str[BUF_SIZE];
    


    Now you have a buffer that can fit 0 to 63 characters + a termination.

    And with gets() you can send BUF_SIZE as parameter, making sure that gets() does never allow you to overflow the buffer.

Reply
  • So all do ever do is to get a single string for each input line? Why then don't you use the gets() function, that (in Keils edition) takes a parameter specifying the size of your buffer?

    But the worst problem - str is expected to be a string. But your declaration is a character. Taking the address of the character and send into sprintf() means that sprintf() only have a valid if it is expected to retrieve a zero-length string (i.e. a string only storing the termination character).

    You must definitely need to make:

    enum {
        BUF_SIZE = 64,
    };
    char str[BUF_SIZE];
    


    Now you have a buffer that can fit 0 to 63 characters + a termination.

    And with gets() you can send BUF_SIZE as parameter, making sure that gets() does never allow you to overflow the buffer.

Children
No data