为什么没有捕获返回值时没有错误?

Kun*_*ava 1 c++ xcode

据我所知,从返回类型函数接收的值必须存储在调用它的位置,否则就是错误的.请解释下面的代码如何正常工作.

#include <iostream>
#include <stdlib.h>
#include<assert.h>
//Returns a pointer to the heap memory location which  stores the duplicate string
char* StringCopy(char* string) 
{                              
    long length=strlen(string) +1;
    char *newString;
    newString=(char*)malloc(sizeof(char)*length);
    assert(newString!=NULL);
    strcpy(newString,string);
    return(newString);
}
int main(int argc, const char * argv[])
{
    char name[30]="Kunal Shrivastava";
    StringCopy(name);   /* There is no error even when there is no pointer which 
                           stores the returned pointer value from the function 
                           StringCopy */
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我在Xcode中使用c ++.

谢谢.

Mik*_*our 6

不要求在C++中使用函数调用(或任何其他表达式)的结果.

如果你想避免可能由于将哑指针返回到动态内存并希望调用者记得释放它而导致的内存泄漏,那么就不要这样做了.返回RAII类型,它将自动清理任何动态资源.在这种情况下,std::string将是理想的; 因为它有一个合适的构造函数,所以甚至不需要编写函数.

通常,如果您正在编写C++,请不要编写C语言.

  • +1,如果可以,我会更多地投票:*如果您正在编写C++*,请不要写C (5认同)
  • *"如果你正在编写C++,就不要写C"*我想在大多数自称为"C++程序员"***的普通人的前额纹身.C-with-classes的历史可以追溯到80年代末,但大多数时候,当我阅读其他人的C++代码时,我觉得如果我和朋友Doc和Marty一起驾驶DeLorean. (2认同)