SFML出现std::bad_alloc错误

std::bad_alloc error with SFML

本文关键字:alloc 错误 bad std SFML 出现      更新时间:2023-10-16

我正在使用SFML进行一个项目,该项目涉及许多带有许多按钮的菜单,因此我正在创建函数,以减少输入,并自动创建和格式化这些按钮。当函数调用已经构建的按钮作为参数时,我的工作非常出色,但我想将其简化为使用字符串,这些字符串将用于构建按钮,这些按钮将存储在向量中。当我尝试这样做时,我收到了这个错误:

Unhandled exception at 0x76a7c41f in Menu.exe: Microsoft C++ exception:
std::bad_alloc at memory location 0x003cd0a0..

我在dbgheap.c:中指出了这一点

 for (;;)
    {
        /* do the allocation
         */
here>>> pvBlk = _heap_alloc_dbg_impl(nSize, nBlockUse, szFileName, nLine, errno_tmp);
        if (pvBlk)
        {
            return pvBlk;
        }
        if (nhFlag == 0)
        {
            if (errno_tmp)
            {
                *errno_tmp = ENOMEM;
            }
            return pvBlk;
        }
        /* call installed new handler */
        if (!_callnewh(nSize))
        {
            if (errno_tmp)
            {
                *errno_tmp = ENOMEM;
            }
            return NULL;
        }
        /* new handler was successful -- try to allocate again */
    }

这是我的代码,以及我更改的内容。

此功能不提供错误:

void page::addLeft(int n, ...)
{
va_list left;
va_start(left, n);
for (int i = 0; i < n; i++)
{
    leftButtons.push_back(va_arg(left, button));
     //takes parameters of type "button", a working custom class
}
va_end(left);
}

此函数为我提供了未处理的异常:std::bad_alloc

void page::addLeft(int n, ...)
{
va_list left;
va_start(left, n);
for (int i = 0; i < n; i++)
{
    std::string s = va_arg(left, std::string);
     //takes a parameter of type "string" and uses it in the default constructor 
     //of button. the default constructor for button works. 
    leftButtons.push_back(button(s));
}
va_end(left);
}

我是SFML的新手,但我认为这不是问题所在。感谢您的任何帮助。

va_arg不适用于std::string。所以在for循环的第一次迭代之后,我们将引用未知内存。使您的示例起作用的一种方法如下:

void page::addLeft(int n, ...)
{
va_list left;
va_start(left, n);
for (int i = 0; i < n; i++)
{
    std::string s = va_arg(left, const char *);
     //takes a parameter of type "string" and uses it in the default constructor 
     //of button. the default constructor for button works. 
    leftButtons.push_back(button(s));
}
va_end(left);
}