2023-07-26 08:59 AM
HARDWARE/SOFTWARE INFO
ISSUE DESCRIPTION
I am writing some code that involves building a string and saving it to a char array using snprintf, then later on saving that string to a char pointer. The string being created will always have an ASCII '%' symbol in it.
Essentially I have found that the running the example code below results in the percent symbol being formatted correctly in the char array string (src_msg), but the formatting changes to be incorrect after I use snprintf to copy the string from the array to the char pointer (dest_msg).
Any ideas why this is happening or how to fix it?
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART1_UART_Init();
printf("Boot!\r\n");
HAL_Delay(2000);
char src_msg[150];
char * dest_msg = malloc(sizeof(char) * 150);
snprintf(src_msg, 150, ",%u%% %u,", 97, 2);
snprintf(dest_msg, 150, src_msg);
printf("Source Message: %s\r\n", src_msg);
printf("\r\n");
printf("Dest Message: %s\r\n", dest_msg);
}
Boot!
Boot!
Source Message: ,97% 2,
Dest Message: ,97 ,
Solved! Go to Solution.
2023-07-26 09:10 AM
If you just want to copy a string, use strcpy instead. Or you could do snprintf(dest_msg, 150, "%s", src_msg).
snprintf uses a printf-style formatting string, yours has "% 2" in it, which is invalid and it doesn't know what to do with.
2023-07-26 09:10 AM
If you just want to copy a string, use strcpy instead. Or you could do snprintf(dest_msg, 150, "%s", src_msg).
snprintf uses a printf-style formatting string, yours has "% 2" in it, which is invalid and it doesn't know what to do with.