Changeset 3573


Ignore:
Timestamp:
Jan 12, 2017, 6:16:05 AM (5 years ago)
Author:
Peter
Message:

fixes #861; throw if allocation fails

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/yat/omic/BamHeader.cc

    r3550 r3573  
    22
    33/*
    4   Copyright (C) 2012, 2013, 2014, 2015, 2016 Peter Johansson
     4  Copyright (C) 2012, 2013, 2014, 2015, 2016, 2017 Peter Johansson
    55
    66  This file is part of the yat library, http://dev.thep.lu.se/yat
     
    225225  void BamHeader::text(const std::string& txt)
    226226  {
    227     read_group_.clear();
    228     program_group_.clear();
     227    BamHeader tmp;
    229228#ifdef YAT_HAVE_HTSLIB
    230     // destroy the old
    231     bam_hdr_destroy(header_);
    232     // and create header pointer
    233     header_ = sam_hdr_parse(txt.size(), txt.c_str());
    234 #endif
    235     // FIXME, handle failures more gracefully than two assertions
    236     // below. If allocations fail, the header should be pristine and
    237     // an exception be thrown.
    238     assert(header_);
    239     header_->l_text = txt.size();
    240     header_->text = (char*)realloc(header_->text, txt.size()+1);
    241     assert(header_->text);
    242     memcpy(header_->text, txt.c_str(), txt.size()+1);
     229    tmp.header_ = sam_hdr_parse(txt.size(), txt.c_str());
     230#else
     231    tmp.header_ = bam_header_init();
     232#endif
     233
     234    // throw if failed
     235    if (!tmp.header_) {
     236      std::ostringstream msg;
     237      msg << "BamHeader::text: " << txt;
     238      throw utility::runtime_error(msg.str());
     239    }
     240    tmp.header_->l_text = txt.size();
     241    tmp.header_->text = (char*)realloc(tmp.header_->text, txt.size()+1);
     242    if (!tmp.header_->text) {
     243      std::ostringstream msg;
     244      msg << "BamHeader::text(1): allocation failed\n" << txt;
     245      throw utility::runtime_error(msg.str());
     246    }
     247    // copy to temporary
     248    memcpy(tmp.header_->text, txt.c_str(), txt.size()+1);
    243249#ifndef YAT_HAVE_HTSLIB
    244     // destroy dict to ensure that things are updated during parsing
    245     if (header_->dict) {
    246       sam_header_free(header_->dict);
    247       header_->dict = 0;
    248     }
    249     sam_header_parse(header_);
    250 #endif
     250    sam_header_parse(tmp.header_);
     251#endif
     252
     253    // everything worked; swap data so this get the new stuff and
     254    // destructor of tmp takes care of the old stuff.
     255    swap(tmp);
    251256  }
    252257
Note: See TracChangeset for help on using the changeset viewer.