【发布时间】:2015-10-15 09:17:00
【问题描述】:
我正在编写一个套接字程序并在一个线程中接收一条消息。但是我遇到了分段错误。 当我直接接收而不启动线程时,没有这样的问题(显示在注释部分)。
在下面的代码中,我直接接收并将其发送给客户端。部分代码如下所示:
if (acceptor->start() == 0)
{
while (1)
{
stream = acceptor->accept();
if (stream != NULL)
{
/*
ssize_t len;
char line[256];
while ((len = stream->receive(line, sizeof(line))) > 0) {
line[len] = 0;
printf("received - %s\n", line);
stream->send(line, len);
*/
pthread_t sniffer_thread;
if( pthread_create( &sniffer_thread, NULL, connection_handler,NULL) < 0)
{
perror("could not create thread");
return 1;
}
//Now join the thread , so that we dont terminate before the thread
pthread_join( sniffer_thread , NULL);
}
delete stream;
}
}
exit(0);
现在,我在线程函数中收到了相同的信息。它显示分段错误。
代码如下所示。
void *connection_handler(void *arg)
{
TCPStream* stream = NULL;
ssize_t len;
char line[256];
while ((len = stream->receive(line, sizeof(line))) > 0)
{
line[len] = 0;
printf("received - %s\n", line);
stream->send(line, len);
}
}
Valgrind 输出的一部分是
==5163== Memcheck, a memory error detector
==5163== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==5163== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==5163== Command: ./appdownload 9999 192.5.60
==5163==
==5163== Thread 2:
==5163== Invalid read of size 4
==5163== at 0x401975: TCPStream::receive(char*, unsigned long, int) (tcpstream.cpp:30)
==5163== by 0x40177B: connection_handler(void*) (appdownload.cpp:68)
==5163== by 0x4E3F181: start_thread (pthread_create.c:312)
==5163== by 0x566947C: clone (clone.S:111)
==5163== Address 0x0 is not stack'd, malloc'd or (recently) free'd
==5163==
==5163==
==5163== Process terminating with default action of signal 11 (SIGSEGV)
==5163== Access not within mapped region at address 0x0
==5163== at 0x401975: TCPStream::receive(char*, unsigned long, int) (tcpstream.cpp:30)
==5163== by 0x40177B: connection_handler(void*) (appdownload.cpp:68)
==5163== by 0x4E3F181: start_thread (pthread_create.c:312)
==5163== by 0x566947C: clone (clone.S:111)
==5163== If you believe this happened as a result of a stack
==5163== overflow in you`enter code here`r program's main thread (unlikely but
==5163== possible), you can try to increase the size of the
==5163== main thread stack using the --main-stacksize= flag.
==5163== The main thread stack size used in this run was 8388608.
【问题讨论】:
-
调试器说什么? 具体是什么指令给出了分段错误?
-
显示 valgrind 输出。
-
虽然解决了NULL流的问题,但我想知道您是否需要删除流指针。我还建议使用 C++ 线程构造而不是 pthread。
标签: c++ multithreading sockets