0

Al ejecutar este código

#include <iostream>

using namespace std;

template <class T>
class huge{
public:

    huge(int bytes) :bytes(bytes) {
        size = sizeof(T);
        maxi = (bytes / size)+1;
        data = (T*)malloc(bytes);
        for (int i=0; i < maxi; i++) data[i] = 0;
        max_value = 1 << 8 * size;
    }

    int gmax() {
        return maxi;
    }

    int gbytes() {
        return bytes;
    }

    T& operator[](int index) {
        return data[index];
    }

    huge operator=(huge x) {
        //data = (T*)malloc(x.gbytes());
        maxi = x.gmax();
        for (int i=0; i < maxi; i++) data[i] = x[i];
        return x;
    }

    huge operator=(T x) {
        data[0] = x;
        for (int i = 1; i < maxi; i++) data[i] = 0;
        return x;
    }

    huge operator+(T x) {
        huge y(bytes);
        y = *this;
        for (int a = 0; x!=0; a++) {
            if (x >= (max_value - y[a]-1) && y[a] != 0) {
                //cout << y[a] << '+' << x << "; x=1"<<endl;
                y[a] += x;
                x = 1;
            }
            else {
                //cout << y[a] << '+' << x << "; x=0"<<endl;
                y[a] += x;
                x = 0;
                break;
            }
        }
        return y;
    }

    huge operator+=(T x) {
        for (int a = 0; x != 0; a++) {
            if (x >= (max_value - data[a] - 1) && data[a] != 0) {
                data[a] += x;
                x = 1;
            }
            else {
                data[a] += x;
                x = 0;
                break;
            }
        }
        return *this;
    }

    huge operator+(huge x) {
        int maximax = (x.gmax() > maxi) ? maxi : x.gmax();
        T resto=0;
        for (int a=0; a < maximax; a++) {
            if (resto >= (max_value - x[a]-1) && x[a] != 0) {
                x[a] += resto;
                resto=1;
            }
            else {
                x[a] += resto;
                resto = 0;
            }
            if (data[a] >= (max_value - x[a]-1) && x[a] != 0) {
                x[a] += data[a];
                resto++;
            }
            else {
                x[a] += data[a];
            }
        }
        return x;
    }

    huge operator+=(huge x) {
        int maximax = (x.gmax() > maxi) ? maxi : x.gmax();
        T resto = 0;
        for (int a = 0; a < maximax; a++) {
            if (resto >= (max_value - data[a] - 1) && data[a] != 0) {
                data[a] += resto;
                resto = 1;
            }
            else {
                data[a] += resto;
                resto = 0;
            }
            if (x[a] >= (max_value - data[a] - 1) && data[a] != 0) {
                data[a] += x[a];
                resto++;
            }
            else {
                data[a] += x[a];
            }
        }
        return x;
    }

    bool operator==(huge x){
        int a = 1;
        if (x.gmax() != maxi)return 0;
        for (int i = 0; i < maxi; i++)a = a && (x[i] = data[i]);
        return a;
    }

    bool operator<(huge x) {
        if (x.gmax() != maxi)return 0;
        for (int i = maxi - 1; i >= 0; i--) if (x[i] != data[i]) return x[i] > data[i];
        return 0;
    }

    bool operator>(huge x) {
        if (x.gmax() != maxi)return 0;
        for (int i = maxi - 1; i >= 0; i--) if (x[i] != data[i]) return x[i] < data[i];
        return 0;
    }

    bool operator>=(huge x) {
        if (x.gmax() != maxi)return 0;
        for (int i = maxi - 1; i >= 0; i--) if (x[i] != data[i]) return x[i] < data[i];
        return 1;
    }

    bool operator<=(huge x) {
        if (x.gmax() != maxi)return 0;
        for (int i = maxi - 1; i >= 0; i--) if (x[i] != data[i]) return x[i] > data[i];
        return 1;
    }

    huge operator<<(int x) {
        huge y(bytes);
        y = *this;
        //cout << endl << !(*this)<<", "<<x << endl;
        T r1 = 0, r2 = 0;
        int z = 1;
        while (x >= 8 * size) {
            x /= 2;
            z *= 2;
        }
        T rec = (size - 1 + 7 * size) - x;
        //cout << x << ',' << z << endl;
        for (int e = 0; e < z; e++) {
            for (int i = 0; i < maxi; i++) {
                r1 = (unsigned int)y[i] >> rec;
                //cout << !y << "<<"<<rec<<'='<<(y[i]>>rec) << ',' << r1 << endl;
                r1 = r1 >> 1;
                //cout << !y << "<<"<<x<<endl;
                y[i] = y[i] << x;
                //cout << !y << endl;
                y[i] = y[i] + r2;
                r2 = r1;
            }
        }
        //cout << !y << endl;
        return y;
    }

    huge operator*(T x) {
        huge y(bytes);
        for (int i = 0; i < x; i++) {
            y += *this;
        }
        return y;
    }

    huge operator*=(T x) {
        for (int i = 1; i < x; i++) {
            *this += *this;
        }
        return *this;
    }

    huge operator*(huge x) {
        huge y(bytes), rec(bytes);
        for (int i = 0; i < x.gmax(); i++) {
            for (int e = 0; e < maxi; e++) {
                rec = x[i];
                //cout <<endl<< !rec << endl;
                rec = rec * data[e];
                //cout << !rec << endl;
                rec = rec << 8 * size * (i + e);
                //cout << !rec << endl;
                y += rec;
                //cout << !rec << endl;
            }
        }
        return y;
    }

    huge operator*=(huge x) {
        huge y(bytes), rec(bytes);
        for (int i = 0; i < x.gmax(); i++) {
            for (int e = 0; e < maxi; e++) {
                rec = x[i];
                //cout <<endl<< !rec << endl;
                rec = rec * data[e];
                //cout << !rec << endl;
                rec = rec << 8 * size * (i + e);
                //cout << !rec << endl;
                y += rec;
                //cout << !rec << endl;
            }
        }
        *this = y;
        return y;
    }

    char* operator!() {
        char* out;
        out = (char*)malloc(sizeof(char)*(size * 16 + 5));
        sprintf_s(out, size * 2 + 5, "");
        int act = 0;
        for (int i = maxi-1; i >=0; i--) {
            if ((data[i] != 0 || i == 0) && act == 0) {
                act = 1;
                sprintf_s(out, size * 16 + 5, "%x", data[i]);
            }
            else if (act == 1)sprintf_s(out, size * 16 + 5, "%s%08x", out, data[i]);
        }
        return out;
    }

private:
    int bytes;
    T *data;
    T size;
    int maxi;
    int max_value;

};

int main() {
    unsigned int x = (1 << 8 * sizeof(unsigned int)) - 1;
    printf("%x\n", x);
    x = x>>sizeof(int)*8-1;
    x = x >> 1;
    printf("\n%x\n", x);
    huge<unsigned int> y(8);
    y = (1 << 8 * sizeof(unsigned int))-1;
    cout << endl << !y << endl;
    y = y + 1+12;
    cout << endl << !y << endl;
    //y = y << 32;
    y = y * y + 1 + 0x10000000;
    cout << endl << !y << endl;
    getchar();
    return 0;
}

escrito en c++ en Visual Studio 2017 se produce una excepción en la linea 13:

for (int i=0; i < maxi; i++) data[i] = 0;

Se produjo una excepción:infracción de acceso de escritura. this->data fue 0x1110112.

Sin embargo cuando defino data como un array y comento la linea del malloc:

#include <iostream>

using namespace std;

template <class T>
class huge{
public:

    huge(int bytes) :bytes(bytes) {
        size = sizeof(T);
        maxi = (bytes / size)+1;
        //data = (T*)malloc(bytes);
        for (int i=0; i < maxi; i++) data[i] = 0;
        max_value = 1 << 8 * size;
    }

    int gmax() {
        return maxi;
    }

    int gbytes() {
        return bytes;
    }

    T& operator[](int index) {
        return data[index];
    }

    huge operator=(huge x) {
        //data = (T*)malloc(x.gbytes());
        maxi = x.gmax();
        for (int i=0; i < maxi; i++) data[i] = x[i];
        return x;
    }

    huge operator=(T x) {
        data[0] = x;
        for (int i = 1; i < maxi; i++) data[i] = 0;
        return x;
    }

    huge operator+(T x) {
        huge y(bytes);
        y = *this;
        for (int a = 0; x!=0; a++) {
            if (x >= (max_value - y[a]-1) && y[a] != 0) {
                //cout << y[a] << '+' << x << "; x=1"<<endl;
                y[a] += x;
                x = 1;
            }
            else {
                //cout << y[a] << '+' << x << "; x=0"<<endl;
                y[a] += x;
                x = 0;
                break;
            }
        }
        return y;
    }

    huge operator+=(T x) {
        for (int a = 0; x != 0; a++) {
            if (x >= (max_value - data[a] - 1) && data[a] != 0) {
                data[a] += x;
                x = 1;
            }
            else {
                data[a] += x;
                x = 0;
                break;
            }
        }
        return *this;
    }

    huge operator+(huge x) {
        int maximax = (x.gmax() > maxi) ? maxi : x.gmax();
        T resto=0;
        for (int a=0; a < maximax; a++) {
            if (resto >= (max_value - x[a]-1) && x[a] != 0) {
                x[a] += resto;
                resto=1;
            }
            else {
                x[a] += resto;
                resto = 0;
            }
            if (data[a] >= (max_value - x[a]-1) && x[a] != 0) {
                x[a] += data[a];
                resto++;
            }
            else {
                x[a] += data[a];
            }
        }
        return x;
    }

    huge operator+=(huge x) {
        int maximax = (x.gmax() > maxi) ? maxi : x.gmax();
        T resto = 0;
        for (int a = 0; a < maximax; a++) {
            if (resto >= (max_value - data[a] - 1) && data[a] != 0) {
                data[a] += resto;
                resto = 1;
            }
            else {
                data[a] += resto;
                resto = 0;
            }
            if (x[a] >= (max_value - data[a] - 1) && data[a] != 0) {
                data[a] += x[a];
                resto++;
            }
            else {
                data[a] += x[a];
            }
        }
        return x;
    }

    bool operator==(huge x){
        int a = 1;
        if (x.gmax() != maxi)return 0;
        for (int i = 0; i < maxi; i++)a = a && (x[i] = data[i]);
        return a;
    }

    bool operator<(huge x) {
        if (x.gmax() != maxi)return 0;
        for (int i = maxi - 1; i >= 0; i--) if (x[i] != data[i]) return x[i] > data[i];
        return 0;
    }

    bool operator>(huge x) {
        if (x.gmax() != maxi)return 0;
        for (int i = maxi - 1; i >= 0; i--) if (x[i] != data[i]) return x[i] < data[i];
        return 0;
    }

    bool operator>=(huge x) {
        if (x.gmax() != maxi)return 0;
        for (int i = maxi - 1; i >= 0; i--) if (x[i] != data[i]) return x[i] < data[i];
        return 1;
    }

    bool operator<=(huge x) {
        if (x.gmax() != maxi)return 0;
        for (int i = maxi - 1; i >= 0; i--) if (x[i] != data[i]) return x[i] > data[i];
        return 1;
    }

    huge operator<<(int x) {
        huge y(bytes);
        y = *this;
        //cout << endl << !(*this)<<", "<<x << endl;
        T r1 = 0, r2 = 0;
        int z = 1;
        while (x >= 8 * size) {
            x /= 2;
            z *= 2;
        }
        T rec = (size - 1 + 7 * size) - x;
        //cout << x << ',' << z << endl;
        for (int e = 0; e < z; e++) {
            for (int i = 0; i < maxi; i++) {
                r1 = (unsigned int)y[i] >> rec;
                //cout << !y << "<<"<<rec<<'='<<(y[i]>>rec) << ',' << r1 << endl;
                r1 = r1 >> 1;
                //cout << !y << "<<"<<x<<endl;
                y[i] = y[i] << x;
                //cout << !y << endl;
                y[i] = y[i] + r2;
                r2 = r1;
            }
        }
        //cout << !y << endl;
        return y;
    }

    huge operator*(T x) {
        huge y(bytes);
        for (int i = 0; i < x; i++) {
            y += *this;
        }
        return y;
    }

    huge operator*=(T x) {
        for (int i = 1; i < x; i++) {
            *this += *this;
        }
        return *this;
    }

    huge operator*(huge x) {
        huge y(bytes), rec(bytes);
        for (int i = 0; i < x.gmax(); i++) {
            for (int e = 0; e < maxi; e++) {
                rec = x[i];
                //cout <<endl<< !rec << endl;
                rec = rec * data[e];
                //cout << !rec << endl;
                rec = rec << 8 * size * (i + e);
                //cout << !rec << endl;
                y += rec;
                //cout << !rec << endl;
            }
        }
        return y;
    }

    huge operator*=(huge x) {
        huge y(bytes), rec(bytes);
        for (int i = 0; i < x.gmax(); i++) {
            for (int e = 0; e < maxi; e++) {
                rec = x[i];
                //cout <<endl<< !rec << endl;
                rec = rec * data[e];
                //cout << !rec << endl;
                rec = rec << 8 * size * (i + e);
                //cout << !rec << endl;
                y += rec;
                //cout << !rec << endl;
            }
        }
        *this = y;
        return y;
    }

    char* operator!() {
        char* out;
        out = (char*)malloc(sizeof(char)*(size * 16 + 5));
        sprintf_s(out, size * 2 + 5, "");
        int act = 0;
        for (int i = maxi-1; i >=0; i--) {
            if ((data[i] != 0 || i == 0) && act == 0) {
                act = 1;
                sprintf_s(out, size * 16 + 5, "%x", data[i]);
            }
            else if (act == 1)sprintf_s(out, size * 16 + 5, "%s%08x", out, data[i]);
        }
        return out;
    }

private:
    int bytes;
    T data[100];
    T size;
    int maxi;
    int max_value;

};

int main() {
    unsigned int x = (1 << 8 * sizeof(unsigned int)) - 1;
    printf("%x\n", x);
    x = x>>sizeof(int)*8-1;
    x = x >> 1;
    printf("\n%x\n", x);
    huge<unsigned int> y(8);
    y = (1 << 8 * sizeof(unsigned int))-1;
    cout << endl << !y << endl;
    y = y + 1+12;
    cout << endl << !y << endl;
    //y = y << 32;
    y = y * y + 1 + 0x10000000;
    cout << endl << !y << endl;
    getchar();
    return 0;
}

el problema se soluciona.

¿A que se debe?

1 respuesta 1

2

Instancias huge con unsigned int y 8 en main:

huge<unsigned int> y(8);

El tamaño (sizeof) de unsigned int es cuatro bytes, por lo que maxi tiene valor tres:

maxi = (bytes / size)+1;
//     (  8   /   4 )+1 = 3
//            2      +1 = 3

Reservas ocho bytes de memoria, que interpretas como punteros a T:

data = (T*)malloc(bytes);

Sabiendo que T es unsigned int y que cada uno de ellos ocupa cuatro bytes, data es capaz de almacenar dos T. Pero tú actúas como si hubiera tres:

for (int i=0; i < maxi; i++) data[i] = 0;
//                 3              ^ <--- 'i' será 0, 1 y 2
//                                       ... pero las únicas posiciones legales son 0 y 1

Acceder a memoria fuera de la memoria solicitada es comportamiento indefinido, con lo que el programa podría haber funcionado o podría haber causado un error (como infracción de acceso) o podría haber hecho que expulsaras demonios de tus fosas nasales; en este caso ha pasado lo segundo.

Sin embargo cuando defino data como un array y comento la línea del malloc el problema se soluciona.

No. El problema no se soluciona, el problema es exactamente el mismo: accedes a memoria fuera de la memoria solicitada (no has solicitado memoria para huge::data), con lo que el programa podría haber funcionado o podría haber causado un error (como infracción de acceso) o podría haber hecho que expulsaras demonios de tus fosas nasales; en este caso ha sucedido lo primero.


No me voy a andar con rodeos. Tu código es un desastre. Estás programando en pero usas herramientas de como malloc. En C++ se usa new/delete en lugar de malloc/free que por cierto éste último no lo estás usando aunque deberías.

La función malloc carece de tipado por lo que es propensa a errores. Tu código podría ser más seguro substituyendo T* por std::vector<T>.

4
  • Al escribir maxi=(bytes/size) como sugeriste me sale una excepción en la linea for (int i=0; i < maxi; i++) data[i] = 0;: Excepción producida en 0x002A1770 en numeros n-bit.exe: 0xC0000005: Infracción de acceso al escribir en la ubicación 0x00000000. el 16 oct. 2019 a las 6:59
  • En ningún momento he sugerido que escribas maxi=(bytes/size). Te sugerí que abandonases la idea de controlar la memoria manualmente y, dado que estás programando en c++ usases std::vector<T>. el 16 oct. 2019 a las 7:02
  • Gracias, Con std::vector<T> se arregla y el problema antes era que devolvía T x=-1 como un huge con bytes = -1 en huge operator+(T x) con lo que el malloc no asignaba memoria. el 16 oct. 2019 a las 8:14
  • Es que NO DEBES USAR malloc MIENTRAS PROGRAMAS EN c++. Si realmente quieres usar memoria dinámica, usa new y delete; entre las bondades de new encuentras que mantiene los tipos de datos y no te permite pedir memoria negativa. el 16 oct. 2019 a las 9:02

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.