Search code examples
c++memory-leaksmemory-managementitoa

What is the best practice of using itoa()


When I use itoa() it needs a char* _DstBuff, what is the best practice here?

#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
  int num = 100;

  // I'm sure here is no memory leak, but it needs to know the length.
  char a[10]; 

  // will this causue memory leak? if yes, how to avoid it?
  // And why can itoa(num, b, 10); be excuted correctly since b
  // has only allocated one char.
  char *b = new char; 

  // What is the difference between char *c and char *b
  // both can be used correctly in the itoa() function
  char *c = new char[10]; 

  itoa(num, a, 10);
  itoa(num, b, 10);
  itoa(num, c, 10);

  cout << a << endl;
  cout << b << endl;
  cout << c << endl;
   return 0;
}

the output is: 100 100 100

So could anyone explain the differenct between char *b = new char; and char *c = new char[10]; here?

I know char *c will dynamiclly allocate 10 chars, but that means char *b will only dynamically allocate 1 char, if I'm right about this, why is the output all correct?

actually which is the best practice of a, b, or c?


Solution

  • Best practice: Don't use it at all.

    Why? Because it's not in the standard.

    What should I do instead? Use std::to_string.

    (If you're really stuck having to use itoa, then use a large local static buffer, like char[512] or so -- if you want to be really really safe you can make the array size sizeof(unsigned long long int) * CHAR_BIT + 2 or something like that so it can always hold any number expressed in any base, plus sign.)