C++ void pointers -


pthread_mutex_t mutexread; int main(int argc, char *argv[]){     pthread_t readerthreads;     pthread_mutex_init(&mutexread, null);     string *fname;     cin>> *fname;     pthread_create(&readerthreads, null, reader_thread, (void*) fname); } void *reader_thread(void *param){     string fname = *(string *) param;     cout<<"filename "<< fname<<endl;     ifstream myfile(fname.c_str());     return null;  } 

the code above throw segmentation fault. messed pointers, not know went wrong , how can fix it?

you declared pointer string, use string , pass address.

pthread_mutex_t mutexread; int main(int argc, char *argv[]){     pthread_t readerthreads;     pthread_mutex_init(&mutexread, null);     string fname;     cin>> fname;     pthread_create(&readerthreads, null, reader_thread, (void*) &fname);     pthread_join(&readerthreads,null); } void *reader_thread(void *param){     string fname = *(string *) param;     cout<<"filename "<< fname<<endl;     ifstream myfile(fname.c_str());     return null;  } 

the other problem don't wait thread termination, stack allocated string may deallocated before thread had time use it... use pthread_join in spawning thread.


Comments

Popular posts from this blog

javascript - Confirm a form & display message if form is valid with JQuery -

Retrieving ETA (estimated time of arrival) with Google Distance Matrix API and public transit as transport mode -

ionic framework - Meteor - Error: Failed to execute 'insertBefore' on 'Node' -