Strange behavior
hello guys!
i have piece of code below
i'm passing f() macro strings both parameters ( f( "at+restore" ), f( "ready" ) ).
both parameters giving sizeof 2.
what not expecting when code goes through first while , put debug command before second while, program prints whole string.
when located code above, getting garbage on first print , correct value second parameter.
if set malloc size manually, it's good. both values printed correctly.
why getting behavior?
thanks in advance!
i have piece of code below
code: [select]
void core::sendat( const __flashstringhelper *_command, const __flashstringhelper *_response )
{
bool completed = true;
start:
char *command = static_cast<char*>( malloc( sizeof *command * sizeof _command ) );
char *response = static_cast<char*>( malloc( sizeof *response * sizeof _response ) );
byte cursor = 0;
while ( ( command[cursor] = pgm_read_byte_near( ( char* ) _command + cursor ) ) != nul )
cursor++;
cursor = 0;
while ( ( response[cursor] = pgm_read_byte_near( ( char* ) _response + cursor ) ) != nul )
cursor++;
debug << f( "command: " ) << command << crlf;
debug << f( "response: " ) << response << crlf;
free( command );
free( response );
}
i'm passing f() macro strings both parameters ( f( "at+restore" ), f( "ready" ) ).
both parameters giving sizeof 2.
what not expecting when code goes through first while , put debug command before second while, program prints whole string.
when located code above, getting garbage on first print , correct value second parameter.
if set malloc size manually, it's good. both values printed correctly.
why getting behavior?
thanks in advance!
sizeof _command gives size of pointer memory, 2 bytes
sizeof *command size of char, 1 byte
and 2 * 1 = 2, feels logic
strlen(_command) want (and need 1 char \0 in malloc if want proper c strings , able print them out)
sizeof *command size of char, 1 byte
and 2 * 1 = 2, feels logic
strlen(_command) want (and need 1 char \0 in malloc if want proper c strings , able print them out)
Arduino Forum > Using Arduino > Programming Questions > Strange behavior
arduino
Comments
Post a Comment