3

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?

Enigma
  • 1,247
  • 3
  • 20
  • 51

4 Answers4

5

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 
Steve Lorimer
  • 27,059
  • 17
  • 118
  • 213
2

Yes you can. No need to memset(), itoa() will overwrite.

Also make sure your buffer is large enough to fit the value.

quarterdome
  • 1,559
  • 2
  • 12
  • 15
2

Yes, you can call itoa twice using the same buffer. Memset is also not necessary, because itoa makes no assumptions about the buffer being empty.

Also note that 10 characters is not long enough for itoa, the string representing a 4 bytes int can be as long as 11 characters + \0 terminator, totalling 12 bytes.

Ishamael
  • 12,583
  • 4
  • 34
  • 52
1

Best practice: Don't use it at all, this function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.

Use std::to_string instead. (to keep in mind, std::to_string may yield unexpected results when used with floating point types and the return values may be substantially different from what std::cout would print)

Vtik
  • 3,073
  • 2
  • 23
  • 38