title: Memory Allocation for threads in C++
body: <p>How to Explicitly Allocate memory to a Thread in C++ ? Am using Windows API for Multi-threading.While running sometimes it executes correctly but sometimes it shows "Heap Corruption","Unhandled Exception".Please guide me</p>
  
  <p>This is the main() where i create the threads.</p>
  
  <pre><code>int main(int argc,char *argv[])
      {
          HANDLE hthread[MAX_THREADS];
          //DWORD threadid;
          FILETIME creation,exit,kernel,user;
          SYSTEMTIME st1,st2;
          //THREADENTRY32 entry;
          char szEntrytime[255],szExittime[255];
  
          directories.push_front(argv[1]);
          files.clear();
          Sem = CreateSemaphore(NULL,MAX_SEM_COUNT,MAX_SEM_COUNT,NULL);
          if (Sem == NULL) 
          {
              printf("CreateSemaphore error: %d\n", GetLastError());
              return 1;
          }
  
          for(int i= 0;i&lt;MAX_THREADS;i++)
          {
              hthread[i] = CreateThread(NULL,0,List,NULL,0,&amp;threadid);
              //hthread[i] = HeapAlloc(GetProcessHeap(),HEAP_NO_SERIALIZE,1024*30);
               if( hthread[i] == NULL )
              {
                  printf("CreateThread error: %d\n", GetLastError());
                  return 1;
              }
          }
  </code></pre>
  
  <p>Inside Thread </p>
  
  <pre><code>while(!directories.empty())
      {
          string path = directories.front();
          string spec = path + "\\" + "*";
          WaitForSingleObject(Sem,0L);
          directories.pop_front();
          ReleaseSemaphore(Sem,1,NULL);
  
          HANDLE hfind = FindFirstFileA(spec.c_str(),&amp;ffd);
          if(hfind == INVALID_HANDLE_VALUE)
              continue;
          cout&lt;&lt; path &lt;&lt;endl;;
          do
          {
              if(strcmp(ffd.cFileName,".") &amp;&amp; strcmp(ffd.cFileName,".."))
              {
                  if(ffd.dwFileAttributes &amp;FILE_ATTRIBUTE_DIRECTORY)
                  {
                      WaitForSingleObject(Sem,0L);
                      directories.push_front(path + "\\" + ffd.cFileName);
                      ReleaseSemaphore(Sem,1,NULL);
                  }
                  else
                  {
                      files.push_back(path + "\\" + ffd.cFileName);
                      Files++;
                  }
              }
          }while(FindNextFileA(hfind,&amp;ffd));
  </code></pre>