由于ID3D11Buffer而导致访问冲突

时间:2014-05-13 18:08:39

标签: c++ arrays directx access-violation directx-11

我尝试创建一个简单的类存储我的模型变量顶点数组和顶点缓冲区。所以我创建了一个myclass数组来动态创建和管理对象。但是什么时候

hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &pieces[counter].g_pVertexBuffer);

此行运行我收到错误“访问违规读取位置”。我尝试了许多事情,但我从未成功过。 如果我不使用类和数组,我不会收到此错误。 Porgram运行没有错误。

MyClass的:

class Piece
{
public:
  double positionX, positionZ,
    red, green,blue;
  bool renderable;
  int type, color, vertexCount;
  XMMATRIX g_WorldPieces;
  ID3D11Buffer* g_pVertexBuffer;
  SimpleVertex* vertices;
  Piece();
  void create(int, int, double, double);
};
Piece::Piece()
{
    g_pVertexBuffer = NULL;
}
 void Piece::create(int t, int c, double pX, double pZ)
 {
   g_pVertexBuffer = NULL;
   renderable = true;
   type = t;
   color = c;
   red=green=blue=0.0f;
   if(color == 1)
      red=green=blue=1.0f;
   positionX = pX;
   positionZ = pZ;
   vertexCount = 0;
 }

  Piece *pieces;//Global variable which define after defining "ID3D11Device*                       g_pd3dDevice = NULL"

并使用myclass的对象:

for(int x=0;x<4;x++)
{
    if(x==2)
    {
        c=0;
        positionZ = 12.5;
    }

    for(int y=0;y<8;y++)
    {
        pieces[counter].create(typeArray[x][y],c,positionX,positionZ);
        positionX += 5;
        switch(pieces[counter].type)
        {
             //Switching object txt. All cases and breaks are fine. 
        }
        fin >> pieces[counter].vertexCount;
        pieces[counter].vertices = new SimpleVertex[vertexCount];
        for(int i=0; i<vertexCountpiyon; i++)
        {
            fin >> pieces[counter].vertices[i].Pos.x >> pieces[counter].vertices[i].Pos.y >> pieces[counter].vertices[i].Pos.z;
            fin >> pieces[counter].vertices[i].Tex.x >> pieces[counter].vertices[i].Tex.y;
            fin >> pieces[counter].vertices[i].Normal.x >> pieces[counter].vertices[i].Normal.y >> pieces[counter].vertices[i].Normal.z;
        }   
        fin.close();
        bd.ByteWidth = sizeof( SimpleVertex ) *pieces[counter].vertexCount;
        ZeroMemory( &InitData, sizeof(InitData) );
        InitData.pSysMem = pieces[counter].vertices;
        hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &pieces[counter].g_pVertexBuffer);//THIS LINE IS MY PROBLEM!
        if( FAILED( hr ) )     return hr;
        counter++;
    }
    positionX = -17.5;
    positionZ += 5;
}

当我获得访问冲突时,计数器为0。

我的项目的源代码:http://1drv.ms/1nKdoUf

1 个答案:

答案 0 :(得分:1)

当您尝试访问程序未分配的内存位置时,会出现访问冲突异常。我查看了你的项目,发现在函数InitDevice中你正在分配一个数组,并将它分配给顶点行747行

pieces[counter].vertices = new SimpleVertex[vertexCount];

在上面的代码中,您使用的是在读取chessBoard.txt时分配的vertexCount,它始终为6(如文件中所定义)。然而,当我使用当前的vertexCount(即,pieces [counter] .vertexCount)时,您需要使用从当前文件读取的顶点计数,程序开始工作并且棋盘可见。尝试将上面的代码语句更改为此

pieces[counter].vertices = new SimpleVertex[pieces[counter].vertexCount];