Simple use of Leaks Instrument on a console application - c++

I would like a simple example on how to use the Leaks tool.
see:
#include <iostream>
int main (int argc, char * const argv[]) {
char *buf = new char[100];
sprintf(buf, "Hello, World!\n");
// insert code here...
std::cout << buf;
return 0;
}
the code above(simple example) should leak the pointer allocated on *buf, right?
with valgrind I would find this very easy after a run
but I just can't find how to do this on the Leaks program
I tried to put sleep(60) but it is still not friendly to me...
thanks,
Jonathan

I've found that Leaks doesn't work all that well with command line applications that exit quickly. I would suggest adding a sleep() like you've done, but add one before the main program logic, and again at the end, so that Leaks is likely to sample the leaked state.
int main() {
sleep(20); // 20s may be enough
{
// do leaky operations, then local variables will go out of scope
}
sleep(20);
}

Related

C/C++ thread calling filling up memory

I am trying to make a server(multithreading) and I run into a problem: it is filling up memory. So I decided to do a simple test. Here is the code in main:
int main(void)
{
int x;
while(1)
{
cin>>x;
uintptr_t thread = 0;
//handle(NULL);
thread = _beginthread(handle, 0, NULL);
if (thread == -1) {
fprintf(stderr, "Couldn't create thread: %d\n", GetLastError());
}
}
}
And here is the 'handle' function:
void handle(void *)
{
;
}
I open task manager, and I am looking there to see how much RAM my process takes.
If the function main is as you see right now, after each press of key 1 and then press enter(so the thing inside the while will execute), the RAM that the process takes increases with 4k(basically, each time the thread is created or something like that, it will leak 4k of memory). If I do this multiple times, it will keep increasing, each time with 4k.
If in the function main I comment this 'thread = _beginthread(handle, 0, 0);' and uncomment this '//handle(NULL);', then the process will not increase it's RAM memory.
Anyone have any ideas how to free that 4k of memory?
I am compiling it with codeblocks, but same result is compiling it with visual studio.
EDIT: from MSDN: "When the thread returns from that routine, it is terminated automatically."
Also I put '_endthread();' in my handle function, but the result IS THE SAME!
Each time around the loop this program creates a new thread. The program never closes any threads.
I think what you have demonstrated is that the memory cost of creating a thread is around 4K.
Presuming you don't want an ever-increasing number of threads, either you should close one before creating another or at least give up when you've got enough.
On further reflection, the above is wrong. I tried your program, and it will not and cannot do what you say, unless there is some important part of the story you've left out.
The line with "cin" just blocks. I pressed enter a few times, but nothing interesting happened. So I took it out.
This program does not leak. Each thread terminates when the handle function finishes.
Here is the code I wrote, adapting yours.
#include <iostream>
#include <Windows.h>
#include <process.h>
using namespace std;
int nthread = 0;
void handle(void *) {
nthread++;
}
int main(int argc, char* argv[]) {
while(nthread < 50000) {
cout << nthread << ' ';
uintptr_t thread = 0;
thread = _beginthread(handle, 0, NULL);
if (thread == -1) {
fprintf(stderr, "Couldn't create thread: %d\n", GetLastError());
break;
}
}
}
It runs 50,000 iterations and uses a grand total of less than 1MB of memory. Exactly as expected.
Something doesn't add up.
Every thread need some memory for it's own infrastructure, that's what the 4K is. When the thread terminates (this depends on your implementation), this 4K will be freed. You should use API functions for joining the the child threads, therefore you should keep the handle(s). Calling the handle function directly is just a function call, no memory is allocated in this case.
EDIT:
Your "handle" function terminates immediately. As far as I know (at least for posix/linux) there are options at creation time for auto-free the memory, or otherwise joining is required. The one thread you see is the "main" thread of the process itself. This way your programm is producing memory leaks.

How to find a way to detect the memory leak in this code?

All, Could any one tell me a good way or tool to detect the memory leak in visual studio for these code? I have tested the crt debug, but while i abort the debug process(shift+f5), the memory leak report doesnot appear in the debug windows.
void fun1()
{
int * pInt = new int;
return;
}
void Execute(void)
{
while(true)
{
cout<<"I will sleep for 1 second..."<<endl;
::Sleep(1000);
fun1();
}
return;
}
int main()
{
Execute();
return 0;
}
Could any one know how to find the memory for above code?
BTW, if i choose to use shared_ptr, the memory leak will not happen again, Right?
The problem here is fairly simple: when you abort a process, leaking memory is more or less taken for granted -- even if your code wouldn't normally leak, aborting it with the debugger is (short of extremely good luck) going to leak memory anyway. As such, most tools that would normally report memory leaks won't when you abort the program with the debugger.
As such, to see a leak report, you just about need to write code that will, at some point, exit on its own instead of requiring you to kill it with the debugger. If you change your code to something like this:
void fun1()
{
int * pInt = new int;
return;
}
void Execute(void)
{
for (int i=0; i<100000; i++)
{
//cout<<"I will sleep for 1 second..."<<endl;
//::Sleep(2000);
fun1();
}
return;
}
int main()
{
Execute();
return 0;
}
By the way, when you pass 2000 as the parameter to Sleep, you should expect it to sleep at least 2 seconds, not just one. For the moment, I've commented out the cout and Sleep, so it should just quickly leak the memory and produce a leak report. With a lot of output and Sleeping, it would do the same, just a lot more slowly and noisily.
Does adding this to the top of your main function not work?
#if defined(DEBUG) | defined (_DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
You have to run in debug mode.
The problem is that while a process is running it is hard for an automated process to tell what memory was leaked. In languages that keep track of references to objects and memory blocks you can do this at any time, you just need to find the blocks that have no references. In C/C++ there is no such thing (unless you implement it yourself, that is), so you can't really tell if a memory block has been leaked or not.
One thing you can do in cases like this is to trigger the function that dumps memory leaks at a point in time in the life of your process that you know should not have any leaks. For example, let's say that you know that your application should not have any leaks at the end of each iteration in the Execute() while loop. Then you could do something like this:
#include <crtdbg.h>
void fun1()
{
int * pInt = new int;
return;
}
void Execute(void)
{
int i = 0;
while(true)
{
cout<<"I will sleep for 1 second..."<<endl;
::Sleep(2000);
fun1();
#ifdef _DEBUG
// dump any leaks every 100 iterations
if (++i % 100 == 0)
_CrtDumpMemoryLeaks();
#endif
}
return;
}
int main()
{
Execute();
return 0;
}
See this page for information about _CrtDumpMemoryLeaks() and other functions of the MSVC CRT library.
I hope this helps.
I have no idea about VS, on Linux I'd use valgrind.

how to execute a particular code in c++ after every 1 minute

I need to make something(i call it a scheduler) that checks the time of the sytem every minute and if the time has changed suppose it is 17:52 and the next moment it is 17:53so at 17:53 it calls a function logupdated
How do i make this simply i m not known to the mutex and all.
Thanks
I am not sure I understand the requirements, but your question reads "how to execute a particular code in c++ after every 1 minute", so, in c++11 you can do this:
#include <thread>
#include <chrono>
int main() {
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(60));
// call your c++ code
}
}
If you want the execution of the task to be independent of the main program flow, consider multithreading.
this example in C, should work also on C++
Note that some people think that I use pointers excessively, I agree, specially with multithreading, it can cause unsafe threads, thus data corruption or even worse, segmentation faults.
However this is the only way to pass arguments to threads as far as I could find.
#include <pthread.h>
int main(int argc, char *argv[]) {
pthread_t thread1;
int variables=10;
pthread_create( &thread1, NULL, scheduler, (void*)&variables);
while(1){
.... do stuff as main program.
}
return 0;
}
void *scheduler (void* variables) {
int vars;
int* p_vars = (int*) variables;
vars = *p_vars;
while (1){
.. do scheduler stuff
sleep (vars);
}
}

Why isn't setjmp saving the stack?

Why isn't setjmp saving the stack?
Consider the following code:
#include <iostream>
jmp_buf Buf;
jmp_buf Buf2;
void MyFunction()
{
for(int i = 0; i < 5; i++)
{
std::cout << i << std::endl;
if(!setjmp(Buf))
longjmp(Buf2, 1);
}
}
int main (int argc, const char * argv[])
{
while(true)
{
if(!setjmp(Buf2))
{
MyFunction();
break;
}
longjmp(Buf, 1);
}
return 0;
}
What I except is that the code will jump back and forth from main to the function and back printing increasing number every time.
What actually happens is that it prints 0 and then 1 infinite number of times. it is as if when it jumps back into the function the stack is reset to defaults. why is it doing it? is there any way I can make it save the stack too?
I know setjmp and longjmp are even worse than goto when it comes to coding style and readable code, but I am experimenting right now, and this code will probably never see the light of a usable application.
Because unfortunately thats not how setjmp works. setjmp copies the current instruction pointer and register set into the jump buffer but it does not copy the stack (obviously be cause the stack is huge). It looks like you want to use some kind of coroutine based techniques. If you want to do this yourself checkout the ucontext procedured (ucontext.h) http://compute.cnr.berkeley.edu/cgi-bin/man-cgi?ucontext.h+3 they will help you to allocate and manage additionaly thread stacks.
or you could use something like Russ Cox's libtask (http://swtch.com/libtask/) which will help do this for you. Or if you want to do it yourself you should take a look at the libtask code (also available through that link). It's pretty easy to read so its a good resource.

"new" operator in multiple threads causes Segmentation Fault

This is related to an issue I have been discussing here and here, but as my investigations have led me away from the STL as the potential issue, and towards "new" as my nemisis, I thought it best to start a new thread.
To reiterate, I am using an arm-linux cross compiler (version 2.95.2) supplied by the embedded platform vendor.
When I run the application below on my Linux PC, it of course works never fails. However when running it on the embedded device, I get segmentation faults every time. Using "malloc" never fails. Synchronising the "new" allocation using the mutex will stop the issue, but this is not practical in my main application.
Can anyone suggest why this might be occurring, or have any ideas how I can get around this issue?
Thanks.
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t _logLock = PTHREAD_MUTEX_INITIALIZER;
static void* Thread(void *arg)
{
int i = 0;
while (i++ < 500)
{
// pthread_mutex_lock(&_logLock);
char* myDyn = (char*) new char[1023];
// char* buffer = (char*) malloc(1023);
// if (buffer == NULL)
// printf("Out of mem\n");
// free(buffer);
delete[] myDyn;
//pthread_mutex_unlock(&_logLock);
}
pthread_exit(NULL);
}
int main(int argc, char** argv)
{
int threads = 50;
pthread_t _rx_thread[threads];
for (int i = 0; i < threads; i++)
{
printf("Start Thread: %i\n", i);
pthread_create(&_rx_thread[i], NULL, Thread, NULL);
}
for (int i = 0; i < threads; i++)
{
pthread_join(_rx_thread[i], NULL);
printf("End Thread: %i\n", i);
}
}
If the heap on your device isn't thread-safe, then you need to lock. You could just write your own new and delete functions that lock for the duration of new or delete -- you don't need to hold the lock across the whole lifetime of the allocated memory.
Check to see if there are compiler switches to make the allocator thread-safe.
As others have stated, chances are that the toolset's default memory allocation behavior is not thread-safe. I just checked with the 2 ARM cross-development toolsets I use the most, and indeed this is the case with one of them.
Most toolsets offer ways of making the libraries thread-safe, either by re-implementing functions or by linking in a different (thread-safe) version of the library. Without more information from you, it's hard to say what your particular toolset is doing.
Hate to say it, but the best information is probably in your toolset documentation.
Yeah, new is probably not threadsafe. You need synchronization mechanisms around the memory allocation and, separately, around the deletion. Look into the Boost.thread library, which provides mutex types that should help you out.
How about using malloc (you say it never fails on the embedded platform) to get the required memory then using placement new (void* operator new[] (std::size_t size, void* ptr) throw()) assuming it is available, for construction. See
new[] operator
Also see stackoverflow article
and
MSDN