【问题标题】:How to debug "Debug Assertion Failed. Buffer too small"?如何调试“调试断言失败。缓冲区太小”?
【发布时间】:2016-12-25 22:19:42
【问题描述】:

当我使用strcpy_s 时,总是出现同样的错误,Debug Assertion failed. L Buffer is too small &&0。有人可以帮我解决吗?我正在使用 Microsoft Visual Studio Ultimate 2012。

struct Nod{
    char *Number;
    char *Name;
    Nod *drt, *stg;
};



void Insert(Nod *&p, char* n, char nr [])
{
    if(p==0 )
        p=makeNod(n, nr);
    else
    {
        ...
    }   
}

Nod * makeNod(char *name, char nr[])
{
    Nod *p=new Nod;
    p->Name=new char [strlen(name)+1];
    strcpy_s(p->Name, strlen(name), name);  //Assertion failed          
    strcpy_s(p->Number, strlen(nr), nr);
    p->stg=p->drt=0;
    return p;  
}
int main()
{

    Nod *p=0;
    int c;
    char nr[9];
    char*name=new char [20];
    cin >> c;
    while(c!=0)
    {
        cout << "Name:  "<< endl;
        cin >> name;
        cout << "Number:  "<< endl;
        cin >> nr;
        Insert(p, name, nr);
        cin >> c;
    }
    return 0;
}

【问题讨论】:

    标签: c++ visual-c++ buffer assertion


    【解决方案1】:

    strcpy_s() 的第二个参数似乎是指向第一个参数的 缓冲区 的大小。由于字符串副本需要复制strlen(name) 字符一个终止空字符,您需要提供一个至少strlen(name)大一个字符的缓冲区.事实上,您确实分配了适当大小的缓冲区!你只是没有通知strcpy_s() 这个事实。

    此外,一旦你克服了这个错误,你会发现你没有为Number 分配任何内存。我还建议实际保护strlen(str) 的结果,因为操作可能很昂贵,例如,当字符串真的很长时。

    【讨论】:

      【解决方案2】:

      首先,strcpy_s 在调试模式下检查了指定的长度 (strlen(name) 是否不足以容纳 name + 终止 \0,因此它断言。

      其次,你没有为p-&gt;Number预留缓冲区。

          Nod *p=new Nod;
          p->Name=new char [strlen(name)+1];
          strcpy_s(p->Name, strlen(name)+1, name); // <-- +1, to not miss the null character at the end
          p->Number=new char [strlen(nr)+1];      // <-- You missed this
          strcpy_s(p->Number, strlen(nr)+1, nr);
      

      最后,使用std::string 并省去这些麻烦。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-29
        • 1970-01-01
        • 2014-10-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多