Not allocating enough memory to pointer?

Hi,

I wrote the following C++ constructor, and I get an error - BUFFER too small on strcpy_s

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Trace::Trace(const char *str)
{
    if (str)
    {
        int len = strlen(str);
        this->m_name = new char[len+1]; // asking for 'len+1' memory elements of char
        strcpy_s(m_name, len, str); // **** I get here an error "BUFFER TOO SMALL" ****
        cout << "start of " << m_name << endl;
    }
    else
    {
        m_name = new char[1];
        m_name[0] = '\0';
    }   
}

m_name is a private data member of type char* .

You have an idea why I get this error
The strcpy_s needs to know the size of the memory including the null terminator. So, code it like this:

1
2
3
   const int len = strlen(str)+1;
   m_name = new char[len];
   strcpy_s(m_name, len, str);
Use len + 1 as size arguments for strcpy_s() or, even better, don't use it at all :)
1
2
3
4
5
6
7
if (str)
    {
        int len = strlen(str);
        this->m_name = new char[len+1]; // asking for 'len+1' memory elements of char
        strcpy_s(m_name, len + 1, str); // **** I get here an error "BUFFER TOO SMALL" ****
        cout << "start of " << m_name << endl;
    }
Awesome! thanks a lot!!

ajh32 and modoran :)
Topic archived. No new replies allowed.