Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid read and write valgrind

the following lines are giving invalid read and write error. Can u please explain what i am missing. i have initialized the variable but still it is causing error.

==26319==   Invalid read of size 4

==26319==    at 0x4035CC: connection_handler (thread.c:26)

==26319==    by 0x4E36A50: start_thread (in /lib64/libpthread-2.12.so)

==26319==    by 0x61E06FF: ???

==26319==   Address 0x53e02c0 is 0 bytes inside a block of size 1 alloc'd

==26319==    at 0x4C27A2E: malloc (vg_replace_malloc.c:270)

==26319==    by 0x40335C: main (send_server.c:154)


==26319==   1 errors in context 3 of 3:

==26319==   Thread 1:

==26319==   Invalid write of size 4

==26319==    at 0x4033C3: main (send_server.c:157)

==26319==  Address 0x53e02c0 is 0 bytes inside a block of size 1 alloc'd

==26319==    at 0x4C27A2E: malloc (vg_replace_malloc.c:270)

==26319==    by 0x40335C: main (send_server.c:154)

Code

int *new_sock = NULL;

while (1) 
{
    client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c); 

    if (client_sock < 0)
    {
        fprintf(stderr,"accept failed\n");
        LOGGER("Accept failed\n");
        continue;
    }

    else
    {   
        LOGGER("\nConnection accepted\n");
        pthread_t sniffer_thread;       //assign thread for each client
        if (NULL ==(new_sock = malloc(1))) //invalid read
            continue;       
        printf("VAlue of new sock %p \n",new_sock);
        *new_sock = client_sock; // invalid write of size 4

        if ( pthread_create( &sniffer_thread , NULL ,  connection_handler , (void*) new_sock) < 0)  //Serving each thread
        {
            fprintf(stderr,"could not create thread\n");
            LOGGER("ERROR could not create thread\n");
            free(new_sock);

        }
        pthread_detach(sniffer_thread);
        LOGGER("Handler assigned\n");
    }

}
like image 693
Tejas Avatar asked Oct 23 '25 21:10

Tejas


1 Answers

You're using an incorrect argument with malloc. You can get the correct size of an int with sizeof(int), which typically yields 4. Try replacing malloc(1) with malloc(sizeof(int)).

new_sock = malloc(1) allocates one byte of memory, and assigns the address of that memory to the variable new_sock.

*new_sock = client_sock; stores an int into that area of memory; writing four bytes into a one byte area of memory overflows the allocation.

Then, when you try to read an int from that allocated memory (supposedly in another thread), one byte is read from the allocated area, but the other three are being read from invalid memory.

like image 114
millinon Avatar answered Oct 25 '25 12:10

millinon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!