简体   繁体   中英

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 aVar ? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM