在函数中声明非指针变量是否存在内存泄漏?

Wes*_*Wes 0 c++ pointers memory-leaks

正如标题所暗示的那样,在函数中声明非指针变量是否会导致内存泄漏?我在互联网上看了一遍,我找到了一个答案,但它是针对C而我不确定是否将同样的规则应用于C++.我目前正在改进我的旧项目,我正在努力提高内存效率.作为一个例子,我有一个加载函数,在启动期间将被调用至少10-20次,我想知道在内存上声明非指针变量会产生什么影响.

void ObjectLoaderManager::loadObject(char FileName[20])
{

    char file[100] = "Resources\Models\"; // Declare object file path
    strncat_s (File, FileName, 20);           // Combine the file path with the input name
    std::string newName;                      // Declare a new scring
    newFile = File;                           // Assign File to the string newFile


    int health = 10;
    // Assign newFile as the name of the newly created object and assign health variable
    // in later parts of the function
}
Run Code Online (Sandbox Code Playgroud)

虽然我确实理解这个函数的部分是明显坏的,而且其中很多都不是我不会做的实践,但是,我很想知道在本地化函数中反复声明非指针变量会产生什么影响.谢谢.这是我在帖子开头提到的文章的链接http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html

Zdr*_*nev 6

不,函数中声明的任何本地变量都在堆栈上分配,因此除非函数被递归多次调用,否则它不是问题.

  • 也就是说,许多编程初学者会在堆栈上声明一个相当大的数组并立即将其吹灭,或者更糟糕的是接近并稍后溢出,这总是很有趣. (2认同)