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.
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;
}
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 copystrlen(name)
characters and a terminating null character you'll need to provide a buffer which is at least one character bigger thanstrlen(name)
. In fact, you did allocate a buffer of the appropriate size! You just didn't informstrcpy_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 ofstrlen(str)
as the operation may be expensive, e.g., when the string is really long.