Hi Guys,

i wrote a program that starts another thread. In one case i thought that i have introduced a memory leak and i should get a segmentation fault but i didn't !! That's kind of puzzled me so i decided to post it here.

#include <iostream>
#include <windows.h>
#include <process.h>

using namespace std;

void  silly( void * );

int main()
{
    cout << "Now in the main() function.\n" << endl;

    int *i = new int(10);
    _beginthread( silly, 0, i );

    delete i;
	cout << "deleted" << endl;
	Sleep( 1000 );
	cout << "didn't crash?" << endl;
}

void  silly( void *arg )
{
	Sleep(100);
	cout << "The silly() function was passed %d\n" << (int*)arg << endl;
}

Output:
Now in the main() function.

deleted
The silly() function was passed %d
00316990
didn't crash?

as you guys can see the silly function is being pointer to a dynamically allocated int and i delete that memory before the silly function prints it. But it still doesn't crash? I was expecting it to give me a dump.

You can't synchronize parent and child threads execution with _beginthread starter. It's possible that the main thread deallocates an array before or after the child thread will use it. In any case you can use deallocated (by C++ RTL) heap memory with or without segmentation fault. So we can see an example of obviously incorrect threading code (in the fullness of your heart you have added uninitialized data printing) - that's all...

So how do i fix this problem? I obviously don't want uninitialized data instead i wan't the pointer to the properly initialized memory being passed and used and not de-allocated till the thread completes. How do i achieve that?

To tell you more, i basically have to call a class 'A' fn from a thread. There is a 'thread' class which has a static fn, that is the fn being passed in beginthread and i want to pass the 'this' pointer of class 'A' as an argument so that i can call class A functions. This idea i got from c++ code on net.

> and not de-allocated till the thread completes. How do i achieve that?
Make the thread responsible for calling delete.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.