Valgrind:在构造函数

时间:2017-07-07 01:17:51

标签: c++ valgrind

我在以下函数中得到的大小为1的读取无效:

ubigint.cpp

ubigint::ubigint (unsigned long that){ 
   //DEBUGF ('~', this << " -> " << uvalue)
   ostringstream convert;  // stream for converting numbers to strings
   convert << that;  // output the number to the stream

    for(string::reverse_iterator rit = convert.str().rbegin(); rit != convert.str().rend(); rit++) // iterate through the string
    {
        ubig_value.push_back(*rit); // push the character
    }  
    size_t current_size = ubig_value.size();
    while(current_size != 0 && ubig_value.back() == '0')
    {
        ubig_value.pop_back();
        current_size--;
    }

}

ubigint.h

// $Id: ubigint.h,v 1.11 2016-03-24 19:43:57-07 - - $

#ifndef __UBIGINT_H__
#define __UBIGINT_H__

#include <exception>
#include <iostream>
#include <limits>
#include <utility>
using namespace std;

#include "debug.h"
#include "relops.h"

    class ubigint {
       friend ostream& operator<< (ostream&, const ubigint&);
       private:
          /*using unumber = unsigned long;
          unumber uvalue {};
          */
          using udigit_t = unsigned char; 
          using ubigvalue_t = vector<udigit_t>; 
          ubigvalue_t ubig_value;

       public:
          void multiply_by_2();
          void divide_by_2();

          ubigint() = default; // Need default ctor as well.
          ubigint (unsigned long);
          ubigint (const string&);

          ubigint operator+ (const ubigint&) const;
          ubigint operator- (const ubigint&) const;
          ubigint operator* (const ubigint&) const;
          ubigint operator/ (const ubigint&)const;
          ubigint operator% (const ubigint&) const;

          bool operator== (const ubigint&) const;
          bool operator<  (const ubigint&) const;


          //helper functions
          string vectorToString(ubigvalue_t& myVector)const;
    };

    #endif

错误讯息:

==4025== Invalid read of size 1
==4025==    at 0x40309C: ubigint::ubigint(unsigned long) (ubigint.cpp:23)
==4025==    by 0x40412F: udivide(ubigint const&, ubigint) (ubigint.cpp:260)
==4025==    by 0x404418: ubigint::operator/(ubigint const&) const (ubigint.cpp:285)
==4025==    by 0x40709D: bigint::operator/(bigint const&) const (bigint.cpp:89)
==4025==    by 0x40CCEB: do_arith(iterstack<bigint>&, char) (main.cpp:35)
==4025==    by 0x40D58F: main (main.cpp:143)

我没有放其他函数,因为我认为问题的原因是构造函数。我注意到我正在将ubig_value.back()与整数0进行比较。我将其更改为char,但仍然无法解决问题。构造函数有什么问题?第23行是ubig_value.pop_back();.当我在不使用valgrind的情况下运行程序时,它运行正常。

1 个答案:

答案 0 :(得分:4)

convert.str()按值返回临时string实例。对convert.str()的两次调用会产生string的不同实例,因此convert.str().rbegin()convert.str().rend()不会形成有效范围 - 它们是不同容器中的迭代器。

此外,rit是一个悬空的迭代器 - 它指向的字符串是一个临时的,在使用迭代器时就消失了。

因此,您的函数表现出不确定的行为。