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;
Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
okami
  • 1,993
  • 6
  • 27
  • 40

1 Answers1

4

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.

Community
  • 1
  • 1
Vlad
  • 34,303
  • 6
  • 78
  • 192
  • 1
    `char* aVar= new char[2]; itoa(2, aVar, 10); delete[] aVar;` – Alex Jasmin Oct 24 '10 at 22:55
  • But it's ugly code. You should avoid manual memory management and functions that operate on fixed size strings. – Alex Jasmin Oct 24 '10 at 22:56
  • 4
    Or just `char aVar[2]; itoa(2, aVar, 10);` – Vlad Oct 24 '10 at 22:57
  • `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 Oct 24 '10 at 23:01
  • @Vlad I was just replicating the code pattern used by the OP. Of course you can put the array on the stack. – Alex Jasmin Oct 24 '10 at 23:07
  • @Alexandre: you are right, I just assumed that the OP wanted just to have the string somewhere. – Vlad Oct 24 '10 at 23:09