开发者

Does itoa delete char?

Why does this give me a memory error?

char* aVar= new char;
itoa(2, aVar, 10);
delete aVar;

Does itoa delete the aVa开发者_Python百科r? How to know if a C++ function deletes the pointer, is there a convention about that?

If I do this then error doesn't occur:

char* aVar= new char;
delete aVar;


itoa needs array long enough to hold the whole value plus null character at the end. In your case, you need to allocate at least 2 chars, otherwise the null character at the end falls on the unallocated memory.

See the documentation on itoa.

For the pure C, sprintf should be a more portable solution:

char aVar[2];
sprintf(aVar, "%d", 2);

(as itoa, according to the documentation, is not universally available).

If you are using C++, the better way of them is to use a stringstream. See this question: Alternative to itoa() for converting integer to string C++? for the discussion.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜