简体   繁体   English

这个功能会泄漏内存吗?

[英]Does this function leak memory?

The function below tests if the input string contains a double. 下面的函数测试输入字符串是否包含double。

bool is_double(const std::string& str)
{
    char* p;
    strtod(str.c_str(), &p);
    return *p == 0;
}

What happens to pointer p after the function returns? 函数返回后指针p会发生什么?

You have two variables to consider: str and p . 您需要考虑两个变量: strp

The string str is passed as a const reference, so it's lifetime must be managed outside the scope of this function, so it cannot be leaked by this function. 字符串str作为const引用传递,因此它的生命周期必须在此函数范围之外进行管理,因此它不能被此函数泄露。

With the character pointer p , we can consider the pointer itself and what it points to. 使用字符指针p ,我们可以考虑指针本身及其指向的对象。 According to the documentation, it is set to "...point to the first character after the number." 根据文档,它设置为“ ...指向数字后的第一个字符”。 Meaning, it points to memory inside the string you've passed; 意思是,它指向您传递的字符串中的内存; it does not get set to newly allocated memory. 它不会设置为新分配的内存。 Since you're already managing the lifetime of str properly, and nothing new has been allocated, you don't have to free what it points to. 由于您已经正确地管理了str的生命周期,并且没有分配任何新内容,因此您不必释放它所指向的内容。 The pointer variable itself is created on the stack, so its lifetime is that of the function. 指针变量本身是在堆栈上创建的,因此它的生存期就是函数的生存期。

So, no, you're not leaking. 因此,不,您不会泄漏。

A resource leak happens when you allocate a resource that becomes unreachable outside a certain scope and you didn't free it nor can get back a reference to it, whether that resource is dynamic memory, mutexes, or any other process-bound resource. 当您分配在某个范围之外变得无法访问的资源,并且您没有释放它也无法获取对其的引用时,无论该资源是动态内存,互斥锁还是任何其他进程绑定资源,都会发生资源泄漏。

In your case, you're creating some variables and using a function that doesn't do any dynamic memory allocation so all of your stuff are in the stack => no memory leak because it's "freed" once you return from the function. 在您的情况下,您正在创建一些变量并使用不执行任何动态内存分配的函数,因此您的所有内容都在堆栈中=> 没有内存泄漏,因为一旦从函数返回它就会“释放”。

由于指针在函数范围内并且未被声明为全局,我相信它将在执行函数后自动擦除。

pointer p will is set by the function to the next character in str after the numerical value. 指针p将由函数设置为数值后的str中的下一个字符。

so it won't leak memory 所以它不会泄漏内存

also you can use 你也可以用

bool is_double(const std::string& str)
{
   double d;
   d = strtod(str.c_str(), NULL);
   return d != 0.0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM