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

Is declaring non pointer variables in a function a memory leak?

本文关键字:是否 存在 内存 泄漏 变量 指针 函数 声明      更新时间:2023-10-16

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

void ObjectLoaderManager::loadObject(char FileName[20])
{
    char file[100] = "ResourcesModels"; // 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
}

虽然我确实理解这个函数的部分是明显的坏,很多这些都不是我不会做的做法,但是,我很想知道一遍又一遍地声明非指针变量会在本地化函数中做什么。谢谢你!这是我在文章开头提到的文章的链接http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html

不,在函数中声明的任何局部变量都是在堆栈上分配的,所以除非函数被递归地调用多次,否则这是没有问题的。