【问题标题】:Segmentation fault in Thread pool线程池中的分段错误
【发布时间】:2010-04-07 22:15:23
【问题描述】:

我正在 Bluez 中创建一个基于蓝牙的服务器程序,它主要处理来自多个设备的连接。我已经构建了两个线程;一个用于扫描远程设备,另一个用于连接正在广播服务的设备。同样,从线程池中为每个新连接的设备提取一个单独的线程,然后通过 RFCOMM 通道与服务器通信。

与远程设备建立连接后,服务器会向远程蓝牙设备发送命令。一旦远程设备收到回复,服务器就会读取该回复并将其存储。

现在,问题是每当我从设备收到回复时,程序就会崩溃,说明“分段错误”。谁能告诉我一个可能的原因。这里给出了执行此操作的代码部分。

void startCommunication( int newSocket )
{


    char buf[MODZ_MAX_DATA_SIZE] = "\0";
        char previousData[ MODZ_MAX_DATA_SIZE ] = "\0"; 
        time_t recvTime, prevRecvTime;
        char dataToBeSent[ 4*MODZ_MAX_DATA_SIZE ] = "\0";
        char *result;

if( sendDataToClient( newSocket, CMD_SEND) == EXT_ERROR )   //send acknowledgement first
    printf("Couldn;t send ack\n");
else { printf("Date send woot! woot! %s\n", CMD_SEND); } 

memset( buf, '0', sizeof(buf) );

while( 1 ){
recvTime = time( ( time_t * )0 );

    if( readDataFromClient( newSocket, buf ) == EXT_ERROR ){
        printf( "Read Error\n" );
        break;
    }
    printf( "Data received = %s\n", buf );

    strcpy( previousData, buf );

    // store the data in a file and send to web

    // check if the web has any data to send and if there is then send
    result = "here we update the challenge";
    strcpy( dataToBeSent, result );
    free( result );
    result = NULL;

    //strcpy( buf, "We will soon update the database" );
    if( sendDataToClient( newSocket, dataToBeSent ) == EXT_ERROR ){
        break;
    }

    }           
close( newSocket );

if( result != NULL ){
    free( result );

}

printf( "\n****************Device disconnected***************\n" );

}

【问题讨论】:

  • 您是否尝试使用valgrind
  • Segmentation Fault 出现在哪里?你用 gdb 调试过吗?
  • 我得到了解决方案...错误发生在免费(结果)部分...有某种线程问题。

标签: linux multithreading sockets bluetooth


【解决方案1】:

一个明显的问题:

result = "here we update the challenge";
strcpy( dataToBeSent, result );
free( result );

您正在释放一个未使用malloc 分配的指针。这很可能会导致分段错误。

以后,请尝试使用 gdb 找出您的程序崩溃的确切位置。

【讨论】:

    猜你喜欢
    • 2017-02-24
    • 1970-01-01
    • 2020-02-29
    • 2018-04-25
    • 2012-05-10
    • 1970-01-01
    • 2022-01-10
    • 2015-06-09
    相关资源
    最近更新 更多