Trouble getting memory allocated for char* in c++

前端 未结 1 705
梦如初夏
梦如初夏 2021-01-25 18:32

So I\'m having trouble allocating memory for a char* being passed into the constructor of my shape class, I keep getting an error saying \"malloc: * error for object 0x

相关标签:
1条回答
  • 2021-01-25 19:23

    This is your problem:

    this->shapeName = (char*) new char(strlen(name)+1);
    

    You're making a single char, and setting its value to strlen(name)+1. The strcpy() then overruns the end of the (single-byte) allocation, and the heap structure 'delete' tries to operate on is broken.

    This is what you want instead (different brackets):

    this->shapeName = new char[strlen(name)+1];
    

    Also, there is a special 'array delete' you must use if you want to be correct:

    delete[] shapeName;
    
    0 讨论(0)
提交回复
热议问题