We help IT Professionals succeed at work.
Get Started

How do I (re-)enable heap memory allocation within a CWinThread-derived class thread function invoked directly from InitInstance?

802 Views
Last Modified: 2013-12-03
This question has morphed into a "can you reproduce the symptom error" problem. - The first comment (from myself) below has a sample program attached, so if someone has a theory as to what may have happened, a quick modification to the sample program should reproduce it easily enough.

I have created a worker thread function wrapped by a CWinThread-derived object.(called ThreadProcObject) -

Within the thread routine (invoked directly from InitInstance - thus Run() and the message pump are not started up) an attempt to allocate some heap memory is made (see example program routines Run1() or Run2()) and, when the error occurs, _malloc_debug() is invoked within the runtime operator new() routine and returns NULL.

At least, this was the symptom in my orignal program, which I have yet to reproduce in the attached sample.

 I originally thought that what was happening is that in between the time the CWinThread-derived object's constructor is invoked and time the thread routine is called by InitInstance (note, before Run1() or Run2() is invoked, the thread goes to sleep first waiting on a "task op ready" event), and that some part of the (heap?) context changes, thus effectively disabling the operator new routine and that this could be resolved by calling some appropriate Afx...? routine to restore the heap context, but this appears to be wrong

An examination of the InitInstance() call to ThreadProc(), that routine's WaitForMultipleObjects-delayed calls to Run1() or Run2() and the memory allocation calls in Run1() or Run(2) should ring a bell if someone has any theories as to how _malloc_dbg() could return NULL if adequate heap memory exists.

I'll award the points if someone actually can reproduce the problem (see the comment below and its attached  program)  within the attached program  - and explain how it happened in the first place.
Comment
Watch Question
Commented:
This problem has been solved!
Unlock 2 Answers and 9 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE