无效的读写valgrind

时间:2016-02-11 06:46:10

标签: c sockets valgrind

以下行给出了无效的读写错误。你可以解释我错过的东西吗?我已初始化变量,但仍导致错误。

==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)

代码

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

}

3 个答案:

答案 0 :(得分:2)

您使用malloc的参数不正确。您可以使用sizeof(int)获取正确的int大小,通常会产生4.尝试将malloc(1)替换为malloc(sizeof(int))

new_sock = malloc(1)分配一个字节的内存,并将该内存的地址分配给变量new_sock

*new_sock = client_sock;将int存储到该内存区域;将四个字节写入一个字节的存储区域会溢出分配。

然后,当您尝试从分配的内存中读取一个int(假设在另一个线程中)时,从分配的区域读取一个字节,但从无效的内存中读取其他三个字节。

答案 1 :(得分:1)

您发布的代码中未显示无效的阅读。

无效写入是由于malloc(3)将以字节分配的空间作为参数。

您正在分配一个字节,并使用int *指向该字节。因此,当您取消引用指针时,您正在访问平台上大于sizeof(int)的{​​{1}}个字节。

请尝试使用1或更好malloc(sizeof (int))

答案 2 :(得分:0)

 if (NULL ==(new_sock = malloc(1)))

必须是

 new_sock = malloc(sizeof(int));
 if(new_sock == NULL)
    continue;

malloc获取size_t参数,该参数是您要分配的内存量字节数。 在您的情况下,您希望为int变量存储空间,然后sizeof(int)返回正确的大小以进行分配。