Home > database >  Why is my static array not cleared by memset?
Why is my static array not cleared by memset?

Time:04-19

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

CodePudding user response:

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.lu" to get correct results for example for 23.007.

  • Related