简体   繁体   English

C ++空指针

[英]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 is "<< fname<<endl;
    ifstream myfile(fname.c_str());
    return NULL;
 }

The code above throw segmentation fault. 上面的代码抛出分段错误。 I probably messed up with my pointers, but I do not know where went wrong and how can I fix it? 我可能弄乱了指针,但是我不知道哪里出了问题以及如何解决?

Two problems: The first and probably cause of the crash is that you have a pointer fname but it doesn't actually point anywhere. 两个问题:崩溃的第一个原因,很可能是崩溃的原因是,您有一个指针fname但实际上它没有指向任何地方。 That leads to undefined behavior when you dereference it. 当取消引用它时,将导致未定义的行为

Unless you need to pass different strings to different threads, it doesn't need to be a pointer, just use the address-of operator & when calling pthread_create . 除非您需要将不同的字符串传递给不同的线程,否则不必是指针,只需在调用pthread_create时使用地址运算符&

You can of course use std::thread instead, and pass the string by value and not have to worry about pointers at all: 当然,您可以改用std::thread ,并按值传递字符串,而不必担心指针:

...
std::string fname;
std::cin >> fname;

std::thread READERthread{&reader_thread, fname);
READERthread.join();
...

And

void reader_thread(std::string fname)
{
    ...
}

The second problem is that you don't wait for the thread to finish before you exit the process. 第二个问题是您不等待线程完成再退出进程。 That will kill the thread. 那会杀死线程。 You either need to join the thread, which waits for it to exit. 您要么需要加入线程,然后等待线程退出。 Or you can detach it, and only exit the main thread (not the process), which leaves the other thread running in the background. 或者,您可以分离它,而仅退出主线程(而不退出进程),这将使另一个线程在后台运行。

You declared a pointer to string , just use a string and pass its address. 您声明了一个指向string的指针,只需使用一个string并传递其地址即可。

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 is "<< fname<<endl;
    ifstream myfile(fname.c_str());
    return NULL;
 }

The other problem is that you don't wait for thread termination, then the stack allocated string may be deallocated before the thread had time to use it... Use pthread_join in the spawning thread. 另一个问题是您不等待线程终止,那么可能在线程有时间使用它之前释放分配给堆栈的字符串...在生成线程中使用pthread_join

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM