C++ 变量周围的堆栈已损坏。(D3D9)

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

本文关键字:D3D9 已损坏 堆栈 变量 周围 C++      更新时间:2023-10-16

我知道有很多类似的问题,但我看不到这个特定问题的任何问题。代码在发布模式下运行良好,但是当我在调试模式下编译时,会给我"变量'索引'周围的堆栈已损坏"。我该如何解决它?提前感谢!

这是有问题的代码:

// 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 的倍数以避免此问题。

请注意,未定义的行为可能导致任何行为,包括程序"运行良好"或至少看起来运行良好。