[Solved] Error in dynamic allocation in C++ [closed]


You should allocate an array of chars, like so:

char *CopyOf(const char *str)
{
    char *copy = new char[strlen(str) + 1];
    strcpy(copy, str);
    return copy;
}

Note that I used brackets, not parentheses. What you were doing with parentheses was initializing a single new char with the value strlen(str) + 1. Then you overran the 1-byte buffer with the call to strcpy. You should strongly consider using std::string; it will save you from a lot of this C heartache.

Also, to get your code to compile, you must add #include <cstring>. Finally, main() should have return type of int.

1

solved Error in dynamic allocation in C++ [closed]