views:

107

answers:

1

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;
+4  A: 

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: http://stackoverflow.com/questions/228005/alternative-to-itoa-for-converting-integer-to-string-c for the discussion.

Vlad
`char* aVar= new char[2]; itoa(2, aVar, 10); delete[] aVar;`
Alexandre Jasmin
But it's ugly code. You should avoid manual memory management and functions that operate on fixed size strings.
Alexandre Jasmin
Or just `char aVar[2]; itoa(2, aVar, 10);`
Vlad
`std::stringstream` is C++ only. Given that the question is tagged with C, you should be recommending `sprintf` rather than `std::stringstream`. **EDIT**: But just realized OP is using `new` in code... retagging.
Billy ONeal
@Billy: indeed. Addressed your comment in the answer update.
Vlad
@Vlad I was just replicating the code pattern used by the OP. Of course you can put the array on the stack.
Alexandre Jasmin
@Alexandre: you are right, I just assumed that the OP wanted just to have the string somewhere.
Vlad