簡體   English   中英

圍繞變量''的C ++堆棧已損壞。 (D3D9)

[英]C++ Stack around the variable '' was corrupted. (D3D9)

我知道有很多類似的問題,但是在這個特定問題上看不到任何問題。 該代碼在Release模式下運行良好,但是給我“變量'indices'周圍的堆棧已損壞”。 在調試模式下編譯時。 我該如何解決? 提前致謝!

這是帶有問題的代碼:

// Create Saturn rings
// create the vertices using the CUSTOMVERTEX struct
#define num_vertices 1000
CUSTOMVERTEX vertices[num_vertices];

nSections = 150;
float outerRadius = (80000000 + escalaa[6]) / escalaa[6];
float innerRadius = (7000000 + escalaa[6]) / escalaa[6];
float endAngle = ToRadians(360);
float beginAngle = ToRadians(0);

float angle = endAngle - beginAngle;

for (unsigned int i = 0; i <= nSections; i+=2)
{
    float t = (float)i / (float)nSections;
    float theta = beginAngle + t * angle;
    float s = (float)sin(theta);
    float c = (float)cos(theta);

    vertices[i] = { c * innerRadius, 0, -1 * (s * innerRadius), { 0.0f, 1.0f, 0.0f }, 4, 2 };
    vertices[i + 1] = { c * outerRadius, 0, -1 * (s * outerRadius), { 0.0f, 1.0f, 0.0f }, 2, 4 };
}



// create a vertex buffer interface called v_buffer
d3ddev->CreateVertexBuffer(num_vertices* sizeof(CUSTOMVERTEX),
    0,
    CUSTOMFVF,
    D3DPOOL_MANAGED,
    &v_buffer,
    NULL);

VOID* pVoid;    // a void pointer

// lock v_buffer and load the vertices into it
v_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, vertices, sizeof(vertices));
v_buffer->Unlock();

// create the indices using an int array
short indices[num_vertices];

int aa=0;
for (int n = 0; n < num_vertices; n += 6)
{
    indices[n] = aa;
    indices[n + 1] = aa + 1;
    indices[n + 2] = aa + 2;

    indices[n + 3] = aa + 2;
    indices[n + 4] = aa + 1;
    indices[n + 5] = aa + 3;
    aa += 2;
}

// create an index buffer interface called i_buffer
d3ddev->CreateIndexBuffer(3 * num_vertices* sizeof(short),
    0,
    D3DFMT_INDEX16,
    D3DPOOL_MANAGED,
    &i_buffer,
    NULL);

// lock i_buffer and load the indices into it
i_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, indices, sizeof(indices));
i_buffer->Unlock();

此循環中斷:

for (int n = 0; n < num_vertices; n += 6)
{
    indices[n] = aa;
    indices[n + 1] = aa + 1;
    indices[n + 2] = aa + 2;

    indices[n + 3] = aa + 2;
    indices[n + 4] = aa + 1;
    indices[n + 5] = aa + 3;
    aa += 2;
}

您需要測試(n + 5) < num_vertices 最終, n將為996,小於num_vertices (1000),因此循環將繼續運行,但是996 + 4為1000,超出了數組范圍。 因此,當n達到996時,對indices[n + 4] (及以后)的讀取或寫入是未定義的行為,對其進行寫入似乎正在破壞堆棧。

請注意,以這種方式更改循環條件將導致indices[996]indices[999]未被初始化! 這意味着您對d3ddev->CreateIndexBuffer()調用可能會觸發對未初始化對象的讀取, 這也是未定義的行為。 您可以考慮將num_vertices重新定義為6的倍數,以避免出現此問題。

請注意,未定義的行為可能導致任何行為, 包括程序“運行良好”或至少看起來確實如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM