2016-02-11 115 views
2

以下幾行給出無效讀寫錯誤。你能解釋我錯過了什麼嗎?我已初始化該變量,但仍然導致錯誤。無效讀寫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"); 
    } 

} 

回答

1

您對malloc使用了不正確的參數。您可以通過sizeof(int)獲得正確的int大小,通常會得到4.嘗試用malloc(sizeof(int))代替malloc(1)

new_sock = malloc(1)分配一個字節的內存,並將該內存的地址分配給變量new_sock

*new_sock = client_sock;將int存儲到該區域的存儲器中;將四個字節寫入內存的一個字節區域會溢出分配。然後,當你試圖從分配的內存(據推測在另一個線程中)讀取一個int時,從分配的區域讀取一個字節,但其他三個字節是從無效內存中讀取的。

1

無效讀不您發佈的代碼所示。

無效寫入是由於malloc(3)需要以字節爲單位分配空間的參數。

您正在分配一個字節,然後用int *指向該字節。因此,當您取消引用指針時,您正在訪問的平臺上的sizeof(int)字節大於1

嘗試使用malloc(sizeof (int))或甚至更好malloc(sizeof *new_sock)來代替。

0

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

必須

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

malloc採取size_t參數是大小要分配的內存量的字節。 在你的情況下,你想要爲int變量存儲空間,那麼sizeof(int)將返回正確的大小以進行分配。