开发者

Thread with and without a memory leak

开发者 https://www.devze.com 2023-04-13 03:06 出处:网络
I\'m stuck with a c++ assignment where I should make a sim开发者_JS百科ple thread and another thread that has the same logic but also have a memory leak.

I'm stuck with a c++ assignment where I should make a sim开发者_JS百科ple thread and another thread that has the same logic but also have a memory leak.

This should just be an easy thread example, even not doing anything useful in itself. So I guess my question is, what is the easiest thread that can be made in c++ and if I have understood correctly that to make it leak memory, I should make a variable, that is never deleted? Also should this "leak" be placed in a loop or made to repeat in some other fashion...because for me just leaving one variable undeleted doesn't seem like a major leak.


This would be enough for a leak:

new char;

You can place it in a loop if you want more, but be careful -

while( true ) {
    new char;
}

brings most systems to a halt quite quickly - they start swapping and become barely usable. IMO you should stick to leaking a couple of objects unless you have other specific requirements.


You could always allocate a large object (such as a big buffer) and never free it; that way a single allocation would be a substantial memory leak.

As well, if you had a thread that was designed as some kind of frequently called worker thread and had a small memory leak there, over the runtime of your program you could easily run into memory problems through "death of a thousand cuts" style leaks.


There is a Boost Thread library, which is probably your easiest option for threads in C++. Yes, a memory leak is just an undeleted variable. If you don't want a one-variable memory leak, just allocate an array of whatever size you deem necessary. new char[x], where x is how many bytes of memory leakage you want

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号