views:

49

answers:

1

i am creating a bluetooth based server program in Bluez which basically handles connections from multiple devices. I have constructed two threads; one to scan the remote devices and another to connect with the devices that are broadcasting the service. Again, a separate thread is extracted from a thread pool for each of the newly connected devices which will then communicate with the server over a RFCOMM channel.

After establishing connection with a remote device, the server will send commands to the remote bluetooth device. Once the remote device a reply, the server reads that reply and stores it.

Now, the problem is whenever I get a reply back from the device the program crashes stating a "segmentation fault". Can anyone tell me a possible cause for this. The part of the code that does this is given here.

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" );

}

+3  A: 

One obvious problem:

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

You are freeing a pointer that was not allocated with malloc. That could well cause a segmentation fault.

In the future, try to use gdb to figure out exactly where your program crashes.

RarrRarrRarr