c++ – C ++: or what does SIGSEGV mean

Question:

I'm making a dynamic numeric class, but when I go to 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 do 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);
    }
    ...
};

Answer:

You receive a SIGSEGV , which is signal 11 , when your program references an invalid memory area. This implies an unexpected interruption of your application, as already noted.

If you pass a vector with only 0 values ​​to the Num constructor you can receive a SIGSEGV because the code ends up accessing a negative index and maybe even removing a value from the other vector 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();
Scroll to Top