简体   繁体   English

由于未知原因,在void函数中创建(大)对象失败

[英]Creating (large) object in void function failing for unknown reasons

I have been puzzled by my program's behavior with certain object allocations for a little while now. 一段时间以来,我对程序的某些对象分配行为感到困惑。

My main() function runs like so: 我的main()函数运行如下:

const int numOpts = 3;
string opts[numOpts] = { "Play", "Settings", "Quit" };
                        // 0       1           2
for (;;)
{
    int choice = input(numOpts); // returns 0, 1, or 2
    if (choice == 0)
    {
        Game b; // 9
        b.start(); // 10
    }
    else if (choice == 1)
        settings(); // edits global variables
    else
        break;
}

However, when I try to put lines 9 and 10 ( Game b; b.start(); ) in their own void function, 但是,当我尝试将第9行和第10行( Game b; b.start(); )放入其自己的void函数时,

static void startGame();

int main()
{
    ...
    if (choice == 0)
        startGame();
    ...
}

static void startGame()
{
    Game b;
    b.start();
}

the program soon crashes (segmentation fault) after one iteration of the for (;;) loop. for (;;)循环的一次迭代后,程序很快崩溃(分段错误)。 In Xcode, main() seems to forget all of its variables after the call to startGame() . 在Xcode中, main()似乎在调用startGame()之后忘记了所有变量。 Similarly, 同样的,

static void startGame()
{
    Game* b = new Game;
    b->start();
    delete b;
}

also fails: however not on my own OS (OS X), but on a Linux machine. 也会失败:但是不是在我自己的OS(OS X)上,而是在Linux机器上。 The output for this is failure looks like this: *** glibc detected *** ./Game: free(): invalid next size (fast): 0x0000000001b41d60 *** ... . 失败的输出如下所示: *** glibc detected *** ./Game: free(): invalid next size (fast): 0x0000000001b41d60 *** ...

Are these problems related? 这些问题相关吗? I suspect that stack data for main() is somehow being freed, but if so, why does the first implementation work, but not the next two? 我怀疑main()堆栈数据会以某种方式被释放,但是如果是这样,为什么第一个实现有效,而接下来的两个无效?

Looks like your Game class writes to memory that is outside of its control, thus corrupting the heap or stack, depending on where you allocate it. 看起来您的Game类将写入其控制范围之外的内存,从而损坏了堆或堆栈,具体取决于您分配的位置。 Look for buffer overruns in "Game". 在“游戏”中查找缓冲区溢出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM