使用itoa()的最佳实践是什么

What is the best practice of using itoa()

本文关键字:是什么 最佳 itoa 使用      更新时间:2023-10-16

当我使用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;
}

输出为:100100100

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

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

实际上,a、b或c的最佳实践是什么?

最佳实践:根本不要使用它

为什么

我该怎么办使用std::to_string

(如果你真的不得不使用itoa,那么就使用一个大的本地静态缓冲区,比如char[512]左右——如果你想真的非常安全,你可以将数组大小设为sizeof(unsigned long long int) * CHAR_BIT + 2或类似的大小,这样它就可以始终保存任何以任何基数表示的数字,加上符号。)

在我提出的这个问题中,您会发现有十几个将整数转换为字符串的高效函数,所有这些函数都分配并返回std::string,因此您不必担心缓冲区溢出。有几个选项可以快速起泡。

您所描述的不是内存泄漏,而是缓冲区溢出。

基本上,你很幸运。如果你只分配了一个字符,但又给它写了四个字符,那么你就超出了分配给你的字符,这就是一个错误。

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

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

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

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

正如下面的评论所说,如果你不需要char*,你可以使用std::string。使用

string d = std::to_string(num);
相关文章: