c++ - delete in threads gives a segmentation fault -


this program counts occurrence of word in line. runs expected, have 2 concerns:

  1. delete tmp commented of (line 57). if uncommented , compiled, executable gives "segmentation fault". oddly, doesn't crash while running in gdb nor valgrind.
  2. lines 65 , 66: ideally these threads need joined. but, getting correct output though not joined. how behaves shared (volatile) variable?
#include <iostream> #include <stdio.h> #include <string.h> #include <pthread.h> #include <unistd.h> #include <fstream> #include <new> #define max_buff 1000  using namespace std; volatile int tcount=0; pthread_mutex_t mymux;  typedef struct data {     string line;     string arg; }tdata;  void *calcwordcount(void *arg) {     tdata *tmp = (tdata *)arg;     string line = tmp->line;     string s = tmp->arg;     int startpos = 0;     int finds = 0;     while ((startpos = line.find(s, startpos)) != std::string::npos)     {             ++finds;             startpos+=1;             pthread_mutex_lock(&mymux);             tcount++;             pthread_mutex_unlock(&mymux);     }     //cout<<endl<<line<<s<<" "<<finds<<endl; } int main(int argc,char *argv[]) {   pthread_t thread_ids[10000];   int cnt=1;   int thread_cnt=0;   void *exit_status;   int targc=argc;   ifstream infile("testfile");     string line;   while(getline(infile,line))   {         while(targc >1)         {               tdata *tmp = new tdata;           tmp->line = line;               tmp->arg = argv[cnt];               pthread_create(&thread_ids[thread_cnt],null,calcwordcount,tmp);               thread_cnt++;               cnt++;               targc--;               //delete tmp;         }     cnt=1;     targc=argc;  } infile.close(); int j; /*for(j=0;j<thread_cnt;j++)     pthread_join(thread_ids[j],&exit_status);*/ cout<<tcount<<endl; return 0; }  

you have undefined behaviour you're calling delete on tmp , thread consuming it.

one fix create , pass (by value) std::shared_ptr rather bare pointer worker thread. can use release , reset methods in main loop. memory released std::shared_ptr once worker thread done it.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -