Search code examples
c++buffer-overflow

The strcpy_s function doesn't work in my code


This function is supposed to copy a char[] into the allocated storage. For some reason the buffer is always too small for this operation.

str(char* f) {

    len = strlen(f);
    txt = (char*)malloc(len); //txt is a pointer to a char
    strcpy_s(txt, len, f);

}

Solution

  • For some reason the buffer is always too small for this operation.

    You forgot to allocate memory for the null terminator. An empty string requires space for one character (the terminator). A string of length one requires space for two characters (1 + 1). A string of length len requires space for len + 1 characters.

    That said:

    • In C, use strdup instead.
    • In C++, don't use strlen, malloc nor strcpy_s (nor strdup). I recommend std::string.