How to debug "Debug Assertion Failed. Buffer too small"?

12.3k views Asked by At

When I'm using strcpy_s always appear the same error, Debug Assertion failed. L Buffer is too small &&0. Can someone help me to solve it? I'm using Microsoft Visual Studio Ultimate 2012.
error message

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;
}
2

There are 2 answers

0
Dietmar Kühl On BEST ANSWER

The second argument to strcpy_s() seems to be the size of the buffer pointed to be the first argument. Since the string copy will need to copy strlen(name) characters and a terminating null character you'll need to provide a buffer which is at least one character bigger than strlen(name). In fact, you did allocate a buffer of the appropriate size! You just didn't inform strcpy_s() about that fact.

Also, once you get over this error you'll find that you haven't allocated any memory for Number. I'd also recommend to actually safe the result of strlen(str) as the operation may be expensive, e.g., when the string is really long.

0
A.S.H On

First, strcpy_s in debug mode has checked that the length specified (strlen(name) is not enough to fit the name + the terminating \0, so it asserts.

Second, you did not reserve a buffer for p->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);

Finally, use std::string and save yourself these headaches.