0

Does anyone know why this causes a segmentation error?

int main ()
{
    udp_client *client = new udp_client("192.168.160.128", 2500);
    client->mysetsockopt("af");
    client->askForFileAndID();
    client->getFileSize();

//this line causes the seg fault error
    std::thread t1(&udp_client::sendFiletoServer, client);


    return 0;
}
Mat
  • 202,337
  • 40
  • 393
  • 406
ineedhelp
  • 59
  • 1
  • 9

2 Answers2

2

Segmentation error can occurred only at runtime, if you have segmentation error, you compiled and linked your program. Probably the problem is that your program finished execution after creating the thread. Try to join your thread t1.

Add: t1.join();

before return from main.

Elvis Oric
  • 1,289
  • 8
  • 22
  • When missing the flag -pthread on compilation, the program will compile fine, but will generate runtime errors. You can try it yourself. I agree, though, he also should join the thread. – Not a real meerkat Aug 17 '15 at 11:52
  • `-pthread` is not used in compile process, that is the reason why you can compile your code, it is used in linking process. Linker will fail without `-pthread`. Correct me if I am wrong. – Elvis Oric Aug 17 '15 at 12:30
  • `-pthread` is not a linking flag. It does add `-lpthread` to the linking process, but it also does some other things on some systems(i.e.: Marking files as reentrant is one example). As I said, missing this flag will not cause a failure on compilation (nor on linking), but will generate a bad program. This is probably because without `-pthread`, some headers will not use symbols from the pthreads library, and therefore need not be linked to it. They will, however, miss some important changes on how they need to work, making them not thread-safe. – Not a real meerkat Aug 17 '15 at 12:49
  • 1
    check http://stackoverflow.com/questions/2127797/gcc-significance-of-pthread-flag-when-compiling – Not a real meerkat Aug 17 '15 at 12:50
  • i added t1.join in the code and -pthread in Project Properties>Settings>Cross G++ Compiler>>Miscellaneous>Other flags, however i still get the error. I will try using pthread instead of std::thread and will post here the result. thanks everyone. – ineedhelp Aug 18 '15 at 01:25
  • changed my code to use fork instead. couldnt make the other options work. thanks everyone. – ineedhelp Aug 18 '15 at 07:07
0

You need to link with pthreads. To acomplish this, just add -pthread to your compilation flags.

Beware that if you want to link statically (bad idea), you'll also need to add some other stuff. Namely: -Wl,--whole-archive -lpthread -Wl,--no-whole-archive

Check https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52590

Not a real meerkat
  • 5,604
  • 1
  • 24
  • 55