Question

I'm using something like this:

char* s = new char;
sprintf(s, "%d", 300);

This works, but my question is why?

When I try to delete it I get an error so this produces a memory leak.

Était-ce utile?

La solution

It "works" because sprintf expects a char* as its first argument, and that what's you are giving him.

However, you really just allocated one char so writing more than one char to it is undefined behavior. It could be that more than one byte gets allocated depending on... the compiler, the host architecture, and so on but you can't rely on it. Actually, anything could happen and you don't want to base your code on such assumptions.

Either allocate more space for your string buffer, or better use a more "modern" approach. In your case it could be something like:

std::string s = std::to_string(300);
// Or, C++03
std::string s = boost::lexical_cast<std::string>(300);

(We are not talking about performance here, but the initial code being incorrect, we could hardly compare anyway).

As an added bonus, this code doesn't leak any memory because std::string takes care of freeing its internal memory upon destruction (s being allocated on the stack, this will happen automatically when it goes out of scope).

Autres conseils

You're creating a one char buffer, then write to it with four chars ("300\0") [don't forget the string termination as I did] so the '3' goes into your allocated memory and the '0' and '0' and the '\0' goes to the next memory positions... that belong to someone else.

C++ does not do buffer overrun checking... so it works until it doesn't...

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top