Har*_*ama 1 c++ pointers memory-management
我正在初始化一个char带有一些随机值的指针,当我试图删除它时,我无法做到.这是为什么?
这是我在做的事情:
int main()
{
    char *s = new char[50];    /* 
                                * I know there is no reason for 
                                * using new if initializing, but 
                                * in order to use delete we need 
                                * to allocate using new.
                                */
    s = "Harry";
    delete s;
    return 0;
}
bil*_*llz 16
如果你真的想用指针练习,你需要修复你的代码.主要的问题是你试图将字符串文字(这里是const char [6])分配给指针s然后尝试通过调用delete调用undefined behavior(UB)来修改它.
char *s = new char[50];    
strcpy(s, "Harry");     // don't assign string literal to it
                        // re-assign pointer to string literal,
                        // lost pre-allocated memory position and caused delete to fail 
                        // it's UB to modify string literal
delete []s;             // new[]/delete[], new/delete need to be called in pair. 
只需使用std::string.
#include <string>
std::string s("Harry"); // no worries
Lst*_*tor 10
问题是在这个任务之后:
s = "Harry";
然后你s不再指向你分配的内存了.它指向一个不同的数组,或者const char[6]说准确.另一个数组未动态分配,并且不在堆上.您不能使用不在delete堆上的变量.
此外,通过s在释放动态分配的内存之前将指针更改为指向其他位置,会引入内存泄漏.
要解决你的代码,可以复制"Harry"到s通过使用阵列strcpy,或使用std::string替代.
| 归档时间: | 
 | 
| 查看次数: | 1593 次 | 
| 最近记录: |