调试断言失败。 BIG_ALLOCATION_ALLIGNMENT

时间:2017-01-11 13:58:05

标签: c++ visual-studio

我试图将用户输入的笔记存储在一个数组中。验证工作正常,但是当我在循环中输入最后一个值时,我得到:

Debug Assertion Failed!
Expression: "(_Ptr_user & (_BIG_ALLOCATION_ALIGNMENT - 1))==0"&&0
An invalid parameter was passed to a function that considers invalid parameters fatal.

我正在努力了解问题所在以及如何解决问题。

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

typedef string noteName;

noteName getNoteName(int i)
{
    bool flag = true;
    noteName Namein;

    do
    {
        cout << "Please enter note name no. " << i + 1 << ": ";
        cin >> Namein;
        cout << "------------------------------------\n";

        if (Namein.length() > 3 || Namein.length() < 2)
        {
            cout << "Sorry, a note name must be 2 or 3 characters long. Please try again.\n";
            flag = false;
        }
        else if (Namein.length() == 3 && Namein[1] != '#')
        {
            cout << "Sorry, the second character of a sharp note name must be #. Please try again.\n";
            flag = false;
        }
        else if ((Namein[0] < 'a' || Namein[0] > 'g') && (Namein[0] < 'A' || Namein[0] > 'G'))
        {
            cout << "Sorry, the first character of a note name must be a letter between A and G. Please try again.\n";
            flag = false;
        }
        else if (isdigit(Namein.back()) == false)
        {
            cout << "Sorry, the last character of a note name must be a number. Please try again.\n";
            flag = false;
        }
        else
        {
            flag = true;
        }
    } while (flag == false);

    return Namein;
}

int main()
{
   const int numNotes = 4;

    noteName NoteNames[numNotes];

    cout << "Hello\n";

    for (int i = 0; i <= numNotes; i++)
    {
        NoteNames[i] = getNoteName(i);
    }

    cout << "Thank you, the note names and lengths you entered were: \n\n";

    for (int i = 0; i <= numNotes; i++)
    {
        cout << i << ". " << NoteNames[i] << "\n";
    }

    cout << "Done!";

    return 0;
}

我想说这与getNoteName() string返回类型有关,因为我还没有回复{{{{{{{ 1}}。

1 个答案:

答案 0 :(得分:1)

noteName NoteNames[numNotes];定义了一个数组,其中NoteNames[numNotes - 1]是您可以访问的最大元素。

你走得更远。这样做的行为是 undefined ,它表现为你观察到的崩溃。

使用for (int i = 0; i < numNotes; i++)或类似内容替换您的循环限制。

(您还有类别名称和变量名称的CamelCase约定从正常情况切换,这会使您的代码难以阅读。)

(我还希望看到constexpr int numNotes = 4;:Google了解详情。)