简体   繁体   中英

C++ char allocation

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.

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).

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

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