使用itoa()的最佳做法是什么

时间:2012-01-10 03:51:15

标签: c++ memory-leaks memory-management itoa

当我使用itoa()时,它需要一个char * _DstBuff,这里的最佳做法是什么?

#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;
}

输出是: 100 100 100

那么有人可以在这里解释char *b = new char;char *c = new char[10];之间的区别吗?

我知道char *c会动态分配10个字符,但这意味着char *b只能动态分配1个字符,如果我对此正确,为什么输出都正确?

实际上哪个是a,b或c的最佳做法?

4 个答案:

答案 0 :(得分:6)

最佳做法:根本不要使用它。

为什么?因为它不符合标准。

我该怎么办?使用std::to_string

(如果您真的不得不使用itoa,那么使用大型本地静态缓冲区,如char[512]左右 - 如果您想真的安全的你可以使数组大小sizeof(unsigned long long int) * CHAR_BIT + 2或类似的东西,所以它总是可以保存任何基数,加号表示的任何数字。)

答案 1 :(得分:2)

this question I posed中,您会找到十几个高效函数,用于将整数转换为字符串,所有这些函数都会分配并返回std::string,因此您无需担心缓冲区溢出。其中有几个选项快速

答案 2 :(得分:1)

您所描述的不是内存泄漏,而是buffer overflow

基本上,你很幸运。如果你只分配一个字符,然后给它写四个字符,你就会超出分配给你的内容,这就是一个错误。

答案 3 :(得分:0)

cout << b << endl;:不正确,是缓冲区溢出。 因为你分配1个字节的内存来包含一个char。但是,你用itoa() 10 + 1chars写上它。

所以你必须分配:char * d = new char[11]; // 10 chars + '\0'(end of string char).

然后使用itoa(num , d , 10);

另外itoa()是非标准的,所以我更喜欢使用标准sprintf(d,"%d",num);

如下面的评论中所述,如果您不需要char*,则可以使用std::string。使用

string d = std::to_string(num);