Thread: How this snprintf function works?

  1. #1
    Registered User
    Join Date
    Feb 2019
    Posts
    97

    How this snprintf function works?

    Hi everyone,

    I have an array of integers that I want to convert into a string. I found that a safe way of doing this task is by calling the snprintf function because it truncates rather than overflowing the buffer.

    However, in the snippet bellow I cannot understand how the second parameter inside the snprintf() works. Why the size should be the size of the data_tx and why each time it is subtracted the index?


    Code:
    char data_tx[16];
    int index = 0;
    uint8_t payload = 3;
    
    uint16_t raw_data[payload];
    uint16_t dummy = 40000;
    
    // Fill in the raw_data array with data
      for (uint8_t i = 0; i < payload; i++) {
        raw_data[i] = dummy++;
      }
    
    // Calculate the size of raw_data array
    uint16_t size = sizeof(raw_data) / sizeof(raw_data[0]);
    
    // Convert raw_data array into a string
      for (uint8_t i = 0; i < size; i++) {
        index += snprintf(&data_tx[index], sizeof(data_tx) - index, "%d", raw_data[i]);
    Why for example this doesn't work?
    Code:
    index += snprintf(&data_tx[index], 5 , "%d", raw_data[i]);
    Thanks in advance
    Nick

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > uint8_t payload = 3;
    > uint16_t raw_data[payload];
    ..
    > index += snprintf(&data_tx[index], 5 , "%d", raw_data[i]);
    std::printf, std::fprintf, std::sprintf, std::snprintf - cppreference.com
    Well the first thing is to NOT lie about your buffer size.

    You're not fitting a great deal in only 6 bytes.

    Don't forget to count the \0 at the end as well.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Feb 2019
    Posts
    97
    • Thank you for your responce Salem,


    I've seen the reference to the link you provided but still is not clear to be how the second parameter performs.. I mean why this syntax
    Code:
    sizeof(data_tx) - index
    Given that for each itteration 5 bytes are written on data_tx[] array it makes sense to me that the buffer size should be 5..

    During the first itteration:
    data_tx[0] // write 5 bytes starting from array index 0
    sizeof(data_tx) - index = 16 - 0 = 16 // why??

    During the second itteration:
    data_tx[5] // write 5 bytes starting from array index 5
    sizeof(data_tx) - index = 16 - 5 = 11 // why??

    During the thrid itteration:
    data_tx[10] // write 5 bytes starting from array index 10
    sizeof(data_tx) - index = 16 - 10 = 6 // why??

  4. #4
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    snprintf() [and vsnprintf()] don't return the number of chars printed (as printf() do), but the number that would be printed. For example:

    Code:
    int size;
    char buffer[10];
    
    size = snprintf( buffer, sizeof buffer, "Frederico was here" );
    // size will be 18, but buffer will be 9 chars + NUL char.
    This is useful to dynamic allocate a buffer:
    Code:
    int size;
    char *buffer, c;
    
    size = snprintf( &c, 1, "%d", value ); // get the # of chars.
    buffer = malloc( size + 1 );
    snprintf( buffer, size + 1, "%d", value ); // again, but filling the allocated buffer.
    PS: I don't know if it's prudent to use:
    Code:
    size = snprintf( NULL, 0, "%d", value );
    So I prefer to use a single char.
    Last edited by flp1969; 01-17-2021 at 08:03 AM.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Sorry, it looks like I got the source and destination arrays mixed up. I thought you were trying to fit 16 somethings into 3 somethings.

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #include<stdint.h>
    
    int main()
    {
      char data_tx[16];
      int index = 0;
      uint8_t payload = 3;
    
      uint16_t raw_data[payload];
      uint16_t dummy = 40000;
    
    // Fill in the raw_data array with data
      for (uint8_t i = 0; i < payload; i++) {
        raw_data[i] = dummy++;
      }
    
    // Calculate the size of raw_data array
      uint16_t size = sizeof(raw_data) / sizeof(raw_data[0]);
    
    // Convert raw_data array into a string
      for (uint8_t i = 0; i < size; i++) {
        index += snprintf(&data_tx[index], sizeof(data_tx) - index, "%d", raw_data[i]);
        printf("Total len=%zd, index=%d\n", strlen(data_tx), index);
      }
    
      return 0;
    }
    Seems OK.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Feb 2019
    Posts
    97
    Thank you for you responce guys,

    Could explain me the purpose of

    Code:
    sizeof(data_tx) - index
    Still I am struggling to understand how the loop working...

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    It's basically telling you how much space you have left in your buffer.

    > snprintf(&data_tx[index], sizeof(data_tx) - index
    Every time you increment index, the place you write to advances, and the space available diminishes.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    Registered User
    Join Date
    Feb 2019
    Posts
    97
    Got it, thank you a lot!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How this function works?
    By Sankait Laroiya in forum C Programming
    Replies: 12
    Last Post: 09-19-2014, 09:19 AM
  2. Finding how a function works..
    By sdbuilt in forum C Programming
    Replies: 7
    Last Post: 09-28-2012, 12:34 PM
  3. Replies: 14
    Last Post: 03-02-2008, 01:27 PM
  4. fprintf works in one function but not in the other.
    By smegly in forum C Programming
    Replies: 11
    Last Post: 05-25-2004, 03:30 PM
  5. My own line function, ALMOST works
    By Shadow12345 in forum C++ Programming
    Replies: 3
    Last Post: 05-18-2002, 04:50 PM

Tags for this Thread