C++: what SIGSEGV means

Asked

Viewed 873 times

3

I’m making a dynamic numeric class, but when I test it, I get the message "Program recived Signal SIGSEGV". I know this is an error with pointers, but why does it occur and how I fix it?

typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;

class Num
{
private:
    vector<uchar> x;
    ushort len;
    ...
public:
    ...
    Num(vector<uchar> other)
    {
        if(other.size() > 8) other.resize(8);

        while(other[other.size() - 1] == 0)
            other.pop_back();

        x = other;
        len = x.size();
    }
    ...
    friend Num operator+(Num l, const Num& rhs)
    {
        Num r = rhs;
        vector<uchar> res (l.x);
        vector<uchar> mod (1, 0);

        while(r.x.size() < res.size()) r.x.push_back(0);
        while(r.x.size() > res.size()) res.push_back(0);

        for(uchar i = 0; i < res.size(); i++)
        {
            mod.push_back((ushort)res[i] + (ushort)r.x[i] > 0xff);
            res[i] += r.x[i];
        }
        if(mod.size() > 0) return (Num(res) + Num(mod));
        return Num(res);
    }
    ...
};
  • Segmentation fault?

  • @LINQ The message I get is "Program Recived Signal SIGSEGV Stack trace is available in 'Call Stack' tab"

  • But it’s a Segmentation fault as LINQ indicated. It means that you accessed an invalid memory address.

1 answer

2


You get a SIGSEGV, which is the sign 11, when your program references an invalid memory area. This implies unexpected interruption of your application, as noted above.

If you pass a vector with only values 0 for the builder Num you may receive a SIGSEGV why the code ends up accessing a negative index and maybe even removing a vector value other already when empty:

    while(other[other.size() - 1] == 0)
        other.pop_back();

I suggest changing to:

    while(!other.empty() && other[other.size() - 1] == 0)
        other.pop_back();
  • That’s the problem, thank you. However, I had to change if (mod.size() > 0) in operator+ for Num nmod = mod; if(nmod.len > 0)

  • You know some place where I can read about it?

  • I do not recommend using the variable len unless it is really necessary to have the size of the vector duplicated on the object. I believe you could solve this problem of if (mod.len > 0) with a local variable. About "subject" you mean SIGSEGV?

  • On the "subject", yes. I created len because when I use const Num, I can’t get access to x.size()

  • To be able to access the size of the vector in a variable const just add a method of type const, declared and implemented as std::size_t size() const { return x.size(); }. About the SIGSEGV suggest Wikipedia in English: https://en.wikipedia.org/wiki/Segmentation_fault

Browser other questions tagged

You are not signed in. Login or sign up in order to post.