cancel
Showing results for 
Search instead for 
Did you mean: 

%% Formatter Bug - snprintf

mikerr
Associate

HARDWARE/SOFTWARE INFO

  • Hardware: NUCLEO-WB55RG Dev Board Device Page 
  • STM32CubeIDE:    Version: 1.13.0
                                   Build: 17399_20230707_0829 (UTC)
  • GGC Assembler All Options: -mcpu=cortex-m4 -g3 -c -x assembler-with-cpp -mfpu=fpv4-sp-d16 -mfloat-abi=hard -mthumb
  • GCC Compiler All Options: -mcpu=cortex-m4 -std=gnu11 -g3 -DUSE_HAL_DRIVER -DDEBUG -DSTM32WB55xx -c -I../../Drivers/BSP/P-NUCLEO-WB55.Nucleo -I../../Drivers/CMSIS/Device/ST/STM32WBxx/Include -I../../Drivers/STM32WBxx_HAL_Driver/Inc/Legacy -I../../Drivers/STM32WBxx_HAL_Driver/Inc -I../../Inc -I../../Drivers/CMSIS/Include -O0 -ffunction-sections -fdata-sections -Wall -fstack-usage -fcyclomatic-complexity -mfpu=fpv4-sp-d16 -mfloat-abi=hard -mthumb
  • GCC Linker All Options: -mcpu=cortex-m4 -T"C:\Users\myname\STM32Cube\Example\UART_Printf\STM32CubeIDE\STM32WB55RGVX_FLASH.ld" --specs=nosys.specs -Wl,-Map="${BuildArtifactFileBaseName}.map" -Wl,--gc-sections -static -mfpu=fpv4-sp-d16 -mfloat-abi=hard -mthumb -Wl,--start-group -lc -lm -Wl,--end-group

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 ,

 

1 ACCEPTED SOLUTION

Accepted Solutions
TDK
Guru

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.

If you feel a post has answered your question, please click "Accept as Solution".

View solution in original post

1 REPLY 1
TDK
Guru

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.

If you feel a post has answered your question, please click "Accept as Solution".