she*_*ngy 0 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;
}
Run Code Online (Sandbox Code Playgroud)
输出为:100 100 100
所以有人能解释这里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
或类似的东西,所以它总是可以保持任何数字表示在任何基地,加号.)
归档时间: |
|
查看次数: |
5177 次 |
最近记录: |