Pregunta

Soy un programador bastante nuevo, así que tengan paciencia conmigo con esto.Estoy usando VC++ 2008.

Recibo este error de mi programa:

Excepción no controlada en 0x68bce2ba (msvcp90d.dll) en z proyecciones.exe:0xC0000005:Ubicación de escritura de infracción de acceso 0x00630067.

Luego, la computadora me lleva a esta página de código que parece bastante confusa y que definitivamente no escribí.Señala que esta sección de código es el código infractor (marcado por "<-computer apunta a esta línea"):

public:
_CRTIMP2_PURE static size_t __CLRCALL_OR_CDECL _Getcat(const facet ** = 0,
    const locale * = 0)
{   // get category value, or -1 if no corresponding C category
    return ((size_t)(-1));
}

_CRTIMP2_PURE void __CLR_OR_THIS_CALL _Incref()
{   // safely increment the reference count
    _BEGIN_LOCK(_LOCK_LOCALE)
        if (_Refs < (size_t)(-1))
            ++_Refs;      <-computer points to this line
    _END_LOCK()
}

_CRTIMP2_PURE facet *__CLR_OR_THIS_CALL _Decref()
{   // safely decrement the reference count, return this when dead
    _BEGIN_LOCK(_LOCK_LOCALE)
    if (0 < _Refs && _Refs < (size_t)(-1))
        --_Refs;
    return (_Refs == 0 ? this : 0);
    _END_LOCK()
}

Lo he reducido a la línea de código de mi propio programa que probablemente esté causando el bloqueo (la cuarta línea de código que comienza con "índice", también etapa = 1):

stringstream index;
string fileName = "";
index.str("");//

index << setw( 3 ) << setfill( '0' ) << stage - 1;

fileName = "positive Z topography-" + index.str() + ".txt";

Lo que me desconcierta es que copié y pegué este código de otro programa que escribí y que se ejecutó cientos de veces sin ningún problema.

Editar:Aquí está el código completo.

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <iomanip>

using namespace std;

int main ()
{
    int dim = 100;
    int steps = 9;  //step 0 = 1, steps = actual steps + 1
    int spread = 5; //number of points averaged to get a slope, must be an odd number
    int halfSpread = (spread - 1)/2; //redefine for eazier use in program (better efficency)

    char * partMap = new char [dim * dim * dim]; // cad data

    // positive and negitive denote the x direction the check is moving in. Positive is  0 -> x, negitive is x -> 0.
    unsigned short int * positiveProjection = new unsigned short int [dim * dim]; //projection arrays
    unsigned short int * negitiveProjection = new unsigned short int [dim * dim];

    unsigned short int * negitiveThickness = new unsigned short int [dim * dim];

    double * negitiveXGradient = new double [dim * dim];
    double * negitiveYGradient = new double [dim * dim];

    stringstream index;
    string fileName;

    ifstream txtFile;
    txtFile.open("3D CAD Part.txt");
    txtFile.read(partMap, dim * dim * dim);
    txtFile.close();


    for (int stage = 1; stage < steps; stage++)
    {

        cout << "stage " << stage << endl;

        //z axis projections
        //projection order is along x then along y, during each step, along z in both directions

        int k = 0; // z axis loop variable

        for (int j = 0; j < dim; j++)
        {
            for (int i = 0; i < dim; i++)
            {
                k = 0;

                while ((k != dim) && partMap[dim * ((dim - 1 - k) + dim * i) + j] < stage) 
                    k++;
                positiveProjection[dim * k + j] = k;

                k = dim;

                while ((k != 0) && partMap[dim * ((dim - 1 - (k - 1)) + dim * i) + j] < stage) 
                    k--;
                negitiveProjection[dim * k + j] = i;

                while ((k != 0) && partMap[dim * ((dim - 1 - (k - 1)) + dim * i) + j] >= stage) 
                    k--;
                negitiveThickness[dim * k + j] = negitiveProjection[dim * k + j] - k;
            }
        }

        // negitive dz/dx gradient
        for (int j = 0; j < dim; j++)
        {

            //first loop to handle the first edge gradients
            for (int i = 0; i < halfSpread; i++)
                negitiveXGradient[(j * dim) + i] = (double(negitiveProjection[(j * dim) + halfSpread + i]) - double(negitiveProjection[j * dim]))/(halfSpread + i); // untested

            //second loop to handle the main middle section
            for (int i = halfSpread; i < dim - halfSpread; i++)
                negitiveXGradient[(j * dim) + i] = (double(negitiveProjection[(j * dim) + i + halfSpread]) - double(negitiveProjection[(j * dim) + i - halfSpread]))/ (spread - 1); // untested

            //third loop to handle the end edge gradients
            for (int i = dim - halfSpread; i < dim; i++)
                negitiveXGradient[(j * dim) + i] = (double(negitiveProjection[(j * dim) + dim - 1]) - double(negitiveProjection[j * dim + i - halfSpread]))/((dim - 1) - i + halfSpread); // untested
        }

        // negitive dz/dy gradient
        for (int i = 0; i < dim; i++)
        {
            //first loop to handle the first edge gradients
            for (int j = 0; j < halfSpread; j++)
                negitiveYGradient[(j * dim) + i] = (double(negitiveProjection[((j + halfSpread) * dim) + i]) - double(negitiveProjection[i]))/(halfSpread + j); // untested

            //second loop to handle the main middle section
            for (int j = halfSpread; j < dim - halfSpread; j++)
                negitiveYGradient[(j * dim) + i] = (double(negitiveProjection[((j + halfSpread) * dim) + i]) - double(negitiveProjection[((j - halfSpread) * dim) + i]))/ (spread - 1); // untested

            //third loop to handle the end edge gradients
            for (int j = dim - halfSpread; j < dim; j++)
                negitiveYGradient[(j * dim) + i] = (double(negitiveProjection[(dim * (dim - 1)) + i]) - double(negitiveProjection[((j - halfSpread) * dim) + i]))/((dim - 1) - j + halfSpread); // untested
        }

        fileName = ""; // reset string and stringstream
        index.str("");//

        index << setw( 3 ) << setfill( '0' ) << stage - 1; // set index, index is -1 of stage due to the program structure

        fileName = "positive Z topography-" + index.str() + ".txt";

        ofstream outputFile1(fileName.c_str(), std::ios::binary | std::ios::out);
        outputFile1.write(reinterpret_cast<const char*>(positiveProjection), streamsize(dim * dim * sizeof(unsigned short int)));
        outputFile1.close();

        fileName = "negitive Z topography-" + index.str() + ".txt";

        ofstream outputFile2(fileName.c_str(), std::ios::binary | std::ios::out);
        outputFile2.write(reinterpret_cast<const char*>(negitiveProjection), streamsize(dim * dim * sizeof(unsigned short int)));
        outputFile2.close();

        fileName = "negitive Z thickness-" + index.str() + ".txt";

        ofstream outputFile4(fileName.c_str(), std::ios::binary | std::ios::out);
        outputFile4.write(reinterpret_cast<const char*>(negitiveThickness), streamsize(dim * dim * sizeof(unsigned short int)));    
        outputFile4.close();

        fileName = "negitive Z X gradient-" + index.str() + ".txt";

        ofstream outputFile5(fileName.c_str(), std::ios::binary | std::ios::out);
        outputFile5.write(reinterpret_cast<const char*>(negitiveXGradient), streamsize(dim * dim * sizeof(double)));
        outputFile5.close();

        fileName = "negitive Z Y gradient-" + index.str() + ".txt";

        ofstream outputFile6(fileName.c_str(), std::ios::binary | std::ios::out);
        outputFile6.write(reinterpret_cast<const char*>(negitiveYGradient), streamsize(dim * dim * sizeof(double)));
        outputFile6.close();
    }
}

Ok, todo está bien hasta el último fragmento de código donde empiezo a enviar mis resultados al disco duro.Utilicé los puntos de interrupción en VC++ y el último punto de interrupción que pasó con éxito antes de que se produjera un error en el punto mencionado anteriormente (el segundo bloque de código que publiqué).Y aparentemente a HTML tampoco le gusta mi código C++.

Ah, también, ahórrese la molestia de pasar por los bucles... deberían estar bien... hay como una docena de bucles allí, no necesita preocuparse por lo que sucede en ellos, son bastante seguros.Sólo tengo problemas con el último trozo.

¿Fue útil?

Solución

A pesar de que los problemas parecen surgir con el último trozo, no significa necesariamente que no hay errores en sus bucles. Si vas fuera de los límites en cualquiera de sus matrices no puede obtener ninguna indicación de ello hasta más tarde.

En el primer bucle while interior de tener

while ((k != dim) && partMap[dim * ((dim - 1 - k) + dim * i) + j] < stage) 
    k++;

lo que significa que potencialmente k podría tener el dim valor cuando haya terminado con el bucle while. La siguiente línea a continuación, hace

positiveProjection[dim * k + j] = k;

que irá fuera de los límites de positiveProjection para cualquier j ya que usted está tratando de índice con dim*dim + j y que sólo tiene dim*dim dimensión.

Otros consejos

  

No soy bastante nuevo programador así que por favor   tengan paciencia conmigo en esto.

Ok. No promesa de hacer burla de ti;)

  

Entonces, el ordenador me lleva a esta   la página de código

Es probable que decir que el depurador de Visual Studio le trae a esta línea. Puede utilizar la función de 'Seguimiento de la pila' para encontrar la ubicación exacta donde las cosas van mal: haga clic en el menú Depurar -> Windows -> Pila de llamadas

.

Sin embargo, no puedo encontrar nada malo en el código. Esta sencilla aplicación funciona perfectamente:

int main()
{

    std::stringstream index;
    std::string fileName = "";
    index.str("");//
    int stage = 1;
    index << std::setw( 3 ) << std::setfill( '0' ) << stage - 1; 
    fileName = "positive Z topography-" + index.str() + ".txt";
    std::cout << "Done with test.\n";
    return 0;
}

Así que con el fin de ayudarle, necesitamos ver más de su código ...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top