使用itoa()的最佳实践是什么
What is the best practice of using 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;
}
输出为: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);
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 派生类销毁的最佳实践是什么
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 在reactor中存储eventHandlers的最佳方式是什么
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 将一系列整数放入类的最佳方法是什么?
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 比较两个节点坐标的最佳方法是什么?
- 在nodejs中使用本机代码的最佳方法是什么?
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- 在 c++ 中解析数据包数据的最佳方法是什么?
- 初始化数组、"memset"或" {//value} "的最佳方法是什么?
- 处理影响跨不同线程共享对象的定时回调的最佳方法是什么?
- 在自定义 std::vector-like 容器中处理指针和非指针模板类型的最佳方法是什么?
- 在向量中查找大于 0(或通常为 k)的最小元素的最佳方法是什么?