C++ 控制台程序(通常)不工作,进程返回 255 (0xFF)

标签 c++ console console-application

<分区>

我用一些树制作了简单的 2D 世界生成器。不幸的是,它并不总是有效。有代码:

#include <assert.h>
#include <iostream>
#include <time.h>
#include <windows.h>
#include <conio.h>
#include <cstdlib>

using namespace std;

int main()
{
    string a[64][16];
    int lvl=10, num;

    srand(time(NULL));

for (;;)
{
    lvl=10;

    //! system("cls");
    for (int i=0; i<16; i++)
    {
        for (int j=0; j<64; j++)
        {
            a[j][i] = " ";
        }
    }


    for (int j=0; j<64; j++)
    {
        num = rand() % 10 + 1;
        cout << num;

        if (num == 1)
        {
            if (lvl > 7)
            {
                lvl--;
            }
        }
        else if (num == 2)
        {
            if (lvl < 15)
            {
                lvl++;
            }
        }
        a[j][lvl] = "O";

        num = rand() % 20 + 1;

        if (num == 7)
        {
            assert( lvl >= 6 );
            a[j][lvl-6] = "^";
            a[j-1][lvl-5] = "/";
            a[j+1][lvl-5] = "\\";
            a[j][lvl-5] = "|";
            a[j-1][lvl-4] = "/";
            a[j+1][lvl-4] = "\\";
            a[j][lvl-4] = "|";
            a[j-1][lvl-3] = "/";
            a[j+1][lvl-3] = "\\";
            a[j][lvl-3] = "|";
            a[j][lvl-2] = "|";
            a[j][lvl-1] = "|";

        }
    }
    cout << endl;

    cout << endl << " +------------------------------------------------------------    ----+" << endl;
    for (int i=0; i<16; i++)
    {
        cout << " |";
        for (int j=0; j<64; j++)
        {
            cout << a[j][i];
        }
        cout << "|" << endl;
    }
    cout << " +----------------------------------------------------------------+"     << endl;
    //! getch();
}
return 0;

} 有时有效,有时只返回 255 (0xFF),有时返回随机代码(我认为),我不知道为什么会这样。

调试器信息:

Starting debugger:
done
Registered new type: wxString
Registered new type: STL String
Registered new type: STL Vector
Setting breakpoints
Debugger name and version: GNU gdb 6.8
Child process PID: 6244
Program received signal SIGSEGV, Segmentation fault.
In std::string::assign () ()
At E:\C++\worldGenerator\main.cpp:59

最佳答案

在 VC++ 2013 中(添加缺少的 header 后),调试器在 std::string::assign() 中引发异常,您在 GDB 中发现了异常。回滚调用堆栈显示这发生在这一行:

             a[j - 1][lvl - 5] = "/";

我修改后的代码中的第 60 行包含在内。此时 j == 0,所以您的问题就在那里 - 索引 a[-1]

通过设置 srand(0) 使测试可重复,它在其他地方失败了:

             a[j + 1][lvl - 4] = "\\";

j == 64 时。您的问题是循环将 j 从 0 迭代到 63,因此 j-1j+1 可能超出范围,不应用于索引 一个[].

    for( int j = 1; j < 63; j++ )

至少允许它运行 - 但可能会或可能不会按您的预期运行。

关于C++ 控制台程序(通常)不工作,进程返回 255 (0xFF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23843854/

相关文章:

c++ - UTF-8解码库

c - printf ("\033c") 是什么意思?

c# - Console当前行怎么写?

c - 键盘输入,不同的按键有不同的响应

c++ - 从文件中读取数据拒绝填充对象

c++ - 输出字符串用 C++ 在 Linux 中覆盖终端上的最后一个字符串

java - 比较乐透号码与中奖乐透号码

c - 像手册页一样显示文本

ruby 诅咒 : how to get pure white

c++ - QT 测试 - 变量/对象失去值(value)