这些指针中的哪一个需要free()或delete()

时间:2019-03-21 21:53:41

标签: c++

我对释放或删除指针感到困惑。 对于我已阅读的内容,我必须将free与malloc,calloc,realloc和new一起使用

但是,如果:

char * hello = "helloworld"; //need to use free()?
char * pointerWmalloc= (char*) malloc(sizeof(char)); 
pointerWmalloc="This need free for sure";
//here need to use free() am I right ? 
char * dupOfHello = strdup(hello); //need to use  free()? 
char * thisWnew= new Char(); // this need delete for sure 
char * charReturnedByFunc= returnchar(); // need to use free() for charReturnedByFunc??

2 个答案:

答案 0 :(得分:2)

char * hello = "helloworld"; //need to use free()?

"helloworld"const char*,而hello现在是对其的动态引用。 (如果您尝试更改字符串中的任何字符或free此内存,则会触发运行时异常)

char * pointerWmalloc = (char*)malloc(sizeof(char));

在重新分配给该内存之前,需要free将其分配给

pointerWmalloc = "This need free for sure";

hello类似,现在指向具有相同限制的const char *。

char * dupOfHello = strdup(hello); //need to use  free()? 

需要free

char * thisWnew = new Char(); // this need delete for sure 

这确实需要delete。另外,除非您将Char归类,否则它不是一类,但我认为您的意思是char()

char * charReturnedByFunc = returnchar(); // need to use free() for charReturnedByFunc??

这很棘手,它完全取决于returnchar()返回指针的内容。 const char*?没有。一个char*由另一个对象或函数拥有?也许。在函数内部分配了char*吗?也许。除非您完全清楚地说明,否则您将不知道returnchar()返回的是malloc还是new的{​​{1}}。

所有这些以及更多的原因是,建议避免使用偏向char*std::unique_ptr的原始指针,避免使用std::shared_ptr偏爱malloc,并避免使用{{1 }}赞成new

答案 1 :(得分:1)

我将在下面的代码中给出注释:

char * hello = "helloworld"; // Do not free/delete pointer
                             // `hello` points to read-only memory
char * pointerWmalloc= (char*) malloc(sizeof(char)); // use free(pointerWmalloc) here
pointerWmalloc="This need free for sure"; // now you created a memory leak since pointerWmalloc now points to read-only memory. So do not free/delete

char * dupOfHello = strdup(hello); // use free(dupOfHello) here (as documented) 
char * thisWnew= new char(); // use delete thisWnew here
char * charReturnedByFunc= returnchar(); // need to read the documentation.
                // could be free, delete, none of the two or something else