Search code examples
c++bufferitoa

Can I reuse the same buffer for subsequent itoa() calls?


I'm wondering if this is safe/sanctioned usage:

char pBuf[10];
itoa(iInt, pBuf, 10);
// pBuf value gets copied elsewhere

//memset(pBuf, 0, sizeof(pBuf)); // Is this necessary?
itoa(iInt2, pBuf, 10);
// pBuf value gets copied elsewhere

Can I reuse the buffer like this?


Solution

  • Yes it is safe.

    itoa will just overwrite the memory, and insert a null terminator at the end. It is this null terminator which makes it safe (assuming of course that your array is large enough)

    Consider the following:

    int iInt = 12345;
    char pBuf[10];
    itoa(iInt, pBuf, 10);
    

    At this point, pBuf will look something like this in memory:

    +---+---+---+---+---+----+-----------------------------+
    | 1 | 2 | 3 | 4 | 5 | \0 | ... unintialised memory ... |
    +---+---+---+---+---+----+-----------------------------+
    

    Then you re-use pBuf:

    int iInt2 = 5;    
    itoa(iInt2, pBuf, 10);
    

    Now pBuf will look like something this in memory:

    +---+----+---+---+---+----+-----------------------------+
    | 5 | \0 | 3 | 4 | 5 | \0 | ... unintialised memory ... |
    +---+----+---+---+---+----+-----------------------------+
           ^
           |
           +---- note the null terminator