Home > Net >  Why does this char array need to be static?
Why does this char array need to be static?

Time:10-18

const char * u8_to_bstr(const uint8_t & u8) {
    static char s[9];   // space for 8-char string
    s[8] = 0;           // terminate string
    char * sp = s;
    for (uint8_t xbit = 0b10000000; xbit > 0; xbit >>= 1) {
        cout << s << endl;
        *(sp  ) = ((u8 & xbit) == xbit) ? '1' : '0';
    }
    return s;
}

I encountered this piece of code studying that converts a uint8 to a string representing its binary. My question is, why do we need the static qualifier for static char s[9]? When I remove the static qualifier I get some very strange behavior but I don't understand why.

CodePudding user response:

The function returns s, which is declared on the stack of this function. Were it not static, it would go out of scope, effectively disappear, once the function returns because all the storage on the stack is made available for reuse once a function returns. By making it static, it’s forced to have a persistent address in memory. However, it’s still bad design - if you call this function from multiple threads, they’ll fight with each other for use of the static memory space.

CodePudding user response:

To expand on what @VorpalSword offered in their answer, it doesn't have to be static. Instead you could dynamically allocate the array. This dynamically allocated memory will remain valid after u8_to_bstr exits.

const char * u8_to_bstr(const uint8_t & u8) {
    const char *s = new char[9];   // space for 8-char string
    s[8] = 0;           // terminate string
    char *sp = s;
    for (uint8_t xbit = 0b10000000; xbit > 0; xbit >>= 1) {
        cout << s << endl;
        *(sp  ) = ((u8 & xbit) == xbit) ? '1' : '0';
    }
    return s;
}

It's a remarkably small change to your code, but it does have implications for how your program works, and you do have to remember later to free up this memory.

delete[] variable_holding_results_ofu8_to_bstr;
  •  Tags:  
  • c
  • Related