释放从函数返回的char*

Eri*_*cyk 2 c++ memory-management char

当我创建一个返回char*或const char*的函数时,是否假设调用函数在完成后必须释放返回的值?否则,它将如何解除分配?我正在寻找一些其他代码调用一个返回char*的函数,并且调用函数中没有delete语句.例:

char* foo();

void bar()
{
    char* result = foo();
    //I should have "delete result" here right?
}
Run Code Online (Sandbox Code Playgroud)

编辑:

所以在我的应用程序中这里是foo:

LPTSTR GetTempPath(LPCTSTR fileName)
{   
    LPTSTR tempPath = new TCHAR[500];
    GetTempPath(500,tempPath);
    printf("Temp Path %ls\n",tempPath);
    PathAppend(tempPath, fileName);
    _tprintf(_T("New temp path: %s\n"), tempPath);
    return tempPath;
}
Run Code Online (Sandbox Code Playgroud)

如果没有新的TCHAR,我不知道如何写这个.我假设这必须删除?有没有更好的方法来写它?

And*_*gia 6

如果您使用的是C++而不是C,那么您应该使用它std::string来解决问题.

  • `std :: string`可以很容易地表示字节缓冲区. (2认同)