I seem to have an issue with dynamic memory allocation.
Below you'll see a derived class that contains a pointer for a name variable that will be dynamically allocated using the void name(const char* name)
method. The function is run by the Product constructor, which sets a name for the product class when the object is created. Here's the class:
namespace sict {
class Product :public Streamable {
char* name_;
public:
Product(const char* name);
virtual ~Product();
void name(const char* name);
}
And here's the name function itself, along with the one argument constructor:
void sict::Product::name(const char * name) {
int g = strlen(name);
name_ = new char[g];
strncpy(name_, name, g);
name_[g] = 0;
}
Product::~Product() {
delete [] name_;
name_ = nullptr;
}
To me this code seems capable enough of created the object then destroying it peacefully whenever it exits the scope of the function it's running in. However, when the function ends and the destructor runs, the program freezes/crashes at delete [] name_
. Running the program on Visual Studio's compiler seems to yield no particular errors (other than the program freezing), but the gcc compiler detects some sort of heap corruption. Would anybody know why this is happening?