Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my static array not cleared by memset?

I want to have a simple float to string converter for an embedded project and would like to not use floating-point snprintf as that would really fill my flash, so i wrote a simple conversion function. I don’t really care for an exact number of decimals nor negative values. This is just a C++ example, i do not want to use STL nor other C++ specific functions as i’m really constrained in terms of space in the real project.

#include <iostream>
#include <cstdio>
#include <cstring>

char msg[100];

typedef uint32_t u32;

char* floatToString(float value)
{
    static char placeholder[100];
    memset(placeholder, '\0', sizeof placeholder);

    auto root = (u32) value;
    auto decimals = (u32) (value * 1000) % 1000;

    snprintf(placeholder, 100, "%lu.%lu", root,
            decimals);

    return placeholder;
}

float weirdVal = 11.35;

int main(){
    snprintf(msg, 100, "%s,%s", floatToString(weirdVal), floatToString(64.876));

    std::cout << msg << '\n';


    return 0;
}

When i test the function and call it, i always get the number passed first. My output is:

11.350,11.350

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are using a common buffer for the converted value.

And since the order of evaluation on your system apparently evaluates the rightmost argument first, you only see the last conversion of 11.35.

You can work around by:

  • printing the converted values separately
  • use another kind of buffering (dynamic, local to caller, …)

Note: You need to format "%lu.%03lu" to get correct results for example for 23.007.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading