Valgrind的分段故障和调试

时间:2012-11-29 03:07:02

标签: c debugging networking network-programming valgrind

我可能在这段代码中遇到了分段问题,使用Valgrind,但我是新手,无法理解它的含义。有人帮我从以下代码中删除错误。 Valgrind的回应也在那里。在代码之后,给出了valgrind的响应。

send_file1=fopen("Document.txt","rb");
cout<<"what";
if(send_file1==NULL) 
{
if(int nofile = sendto(conn_sock , NoFile , sizeof(NoFile) , 0 ,(struct sockaddr *)&client_addr , sizeof(client_addr))==-1) //Sendin ACK
{
    cout<<"ERROR"<<endl;
    exit(1);
}

}
if(int accept = sendto(conn_sock , accepted , sizeof(accepted) , 0 ,(struct sockaddr *)&client_addr , sizeof(client_addr))==-1) //Sendin ACK
{
    cout<<"ERROR"<<endl;
    exit(1);
}
cout<<"CHECK"<<endl;
fseek (send_file1 , 0 , SEEK_END);
length = ftell (send_file1);
rewind (send_file1);

// allocate memory to contain the whole file:
Buffer = (char*) malloc (sizeof(char)*length);
if (Buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

// copy the file into the buffer:
Read_byt = fread (Buffer,1,length,send_file1);
if (Read_byt != length) {fputs ("Reading error",stderr); exit (3);}



==11113== Invalid read of size 2
==11113==    at 0x41C924D: fseek (fseek.c:40) 
==11113==    by 0x8049B34: main (in /home/mishal/Downloads/Work Moby/Computer     Networks/Project/Phase 1/execute)
==11113==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==11113==  
==11113== 
==11113== Process terminating with default action of signal 11 (SIGSEGV)
==11113==  Access not within mapped region at address 0x0
==11113==    at 0x41C924D: fseek (fseek.c:40)
==11113==    by 0x8049B34: main (in /home/mishal/Downloads/Work Moby/Computer Networks/Project/Phase 1/execute)
==11113==  If you believe this happened as a result of a stack
==11113==  overflow in your program's main thread (unlikely but
==11113==  possible), you can try to increase the size of the
==11113==  main thread stack using the --main-stacksize= flag.
==11113==  The main thread stack size used in this run was 8388608.
==11113== 
==11113== HEAP SUMMARY:
==11113==     in use at exit: 9,067 bytes in 8 blocks
==11113==   total heap usage: 9 allocs, 1 frees, 9,419 bytes allocated
==11113== 
==11113== LEAK SUMMARY:
==11113==    definitely lost: 500 bytes in 5 blocks
==11113==    indirectly lost: 0 bytes in 0 blocks
==11113==      possibly lost: 0 bytes in 0 blocks
==11113==    still reachable: 8,567 bytes in 3 blocks
==11113==         suppressed: 0 bytes in 0 blocks
==11113== Rerun with --leak-check=full to see details of leaked memory
==11113== 
==11113== For counts of detected and suppressed errors, rerun with: -v
==11113== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 19 from 8)

1 个答案:

答案 0 :(得分:1)

使用-g(调试标志)编译代码,以便从valgrind获取更多信息,例如源代码中错误的位置。看起来您正在打开的文件不存在,因此请确保检查外部呼叫的返回值(即fopenfseek,...)。