What is the best practice of using itoa()

6.5k views Asked by At

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?

4

There are 4 answers

6
Kerrek SB On BEST ANSWER

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.)

1
Hicham On

cout << b << endl; : is incorrect, it is a buffer overflow. because you allocate 1 byte of memory to contain one char. but, you write on it with itoa() 10+1chars.

so you have to allocate : char * d = new char[11]; // 10 chars + '\0'(end of string char).

then use itoa(num , d , 10);

in addition itoa() is non standard, so i prefer to use the standard sprintf(d,"%d",num);

and as said in the comment below, if you dont need char* and you can use std::string. use

string d = std::to_string(num);
0
Jonathon Reinhart On

What you are describing is not a memory leak, but rather a buffer overflow.

Basically, you are getting lucky. If you allocate only one character, but then write four characters to it, you are overrunning what has been allocated to you, and this is a bug.

0
Ben Voigt On

In this question I posed, you'll find a dozen efficient functions for converting an integer into a string, all of which allocate and return a std::string so you needn't worry about buffer overflow. And several options in there are blistering fast.