【问题标题】:what is wrong with the following code以下代码有什么问题
【发布时间】:2012-03-09 11:29:40
【问题描述】:

以下函数从 rabin_polynomial 结构中获取文件偏移量,打开 input_file 以生成 md5 指纹并将结果写入 fpfile

我的问题是它似乎有时使用相同的 chunk_buffer 内容,它会为不同长度的块生成相似的指纹。

可能是什么原因?

我已经分别用其他输入测试了 md5 函数,它生成了正确的摘要。

   int write_rabin_fingerprints_to_binary_file(FILE *fpfile,FILE *input_file,
    struct rabin_polynomial *head)
{        
    struct rabin_polynomial *poly=head;
    unsigned char fing_print[33]={'\0'};
    size_t bytes_read;
      while(poly != NULL)
        {    
       char *chunk_buffer;
       chunk_buffer = (char*) malloc ((poly->length));  
       bytes_read=fread (chunk_buffer,1, poly->length,input_file);          
               if(bytes_read!=poly->length)
                {
                   printf("Error reading from%s ",input_file);
                   return -1;
                }
       strncpy((char*)fing_print,md5(chunk_buffer).c_str(),32);     
       size_t ret_val=fprintf(fpfile, "%llu\t%lu\t%s\n",poly->start,
                                       poly->length,fing_print);

              if(ret_val == 0)
               {
                  fprintf(stderr, "Could not write rabin polynomials to file.");
                  return -1;
               }

         poly=poly->next_polynomial;
      free(chunk_buffer);
        }

   return 0;
}

编辑:

我正在使用 Visual Studio 2010 运行此程序。在 ma​​lloc() 行中将类型转换为 char * 会产生问题吗?

读取的字节数与参数中指定的一样。

【问题讨论】:

  • 你需要在某处检查 fread 的返回值

标签: c malloc md5 collision fingerprint


【解决方案1】:

导致此类错误的代码没有任何问题。我刚刚发现它的发生是因为 零长度字符串,也称为 文件漏洞。

【讨论】:

    【解决方案2】:
       int write_rabin_fingerprints_to_binary_file(FILE *fpfile,FILE *input_file
         , struct rabin_polynomial *head)
    {        
        struct rabin_polynomial *poly;
        unsigned char fing_print[33];
    
        for (poly=head; poly != NULL;poly=poly->next_polynomial )   {    
           char *chunk_buffer;
           int retval;
    
           chunk_buffer = malloc (1+poly->length);  
           retval = fread (chunk_buf,1, poly->length,input_file);
    
                /* check retval here */
    
           chunk_buff[poly->length] = 0;     
           strncpy(fing_print,md5(chunk_buffer).c_str(), sizeof fing_print);
           fing_print[sizeof fing_print -1] = 0;
           retval = fprintf(fpfile, "%llu\t%lu\t%s\n"
                          ,poly->start, poly->length, fing_print);
    
                  if(retval <= 0)
                   {
                      fprintf(stderr, "Could not write rabin polynomials to file.");
                      return -1;
                   }
            free(chunk_buffer);
            }
    
       return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-10
      • 2011-02-28
      • 2017-02-17
      • 1970-01-01
      相关资源
      最近更新 更多