为什么我的 C++ 代码会发生内存泄漏?

Why do I have a memory leak in my c++ code?

我是 c++ 的新手,我有编译但不会发布到 linux 的代码,因为它说我在错误中有内存泄漏。请帮我找出代码中的错误。 Linux 使用 valgrind,它可以发现泄漏。 请帮我找到错误并修复它。

内存泄漏的输出:

==6858== Memcheck, a memory error detector
==6858== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==6858== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==6858== Command: ws
==6858==
Enter the following Data:
----------------------
lukE
sky
fett
feT
Jack
!
----------------------
Star Wars phone direcotry search
-------------------------------------------------------
Enter a partial name to search (no spaces) or enter '!' to exit
> lukE
Luke Skywalker: (301) 555-0630
Enter a partial name to search (no spaces) or enter '!' to exit
> sky
Luke Skywalker: (301) 555-0630
Enter a partial name to search (no spaces) or enter '!' to exit
> fett
Jango Fett: (905) 555-6016
Boba Fett: (905) 555-9382
Enter a partial name to search (no spaces) or enter '!' to exit
> feT
Jango Fett: (905) 555-6016
Boba Fett: (905) 555-9382
Enter a partial name to search (no spaces) or enter '!' to exit
> Jack
Enter a partial name to search (no spaces) or enter '!' to exit
> !
Thank you for using Star Wars directory.

----------------------------------
Broken Phone Book phone direcotry search
-------------------------------------------------------
badDataFile.txt file not found!
Thank you for using Broken Phone Book directory.
==6858==
==6858== HEAP SUMMARY:
==6858==     in use at exit: 568 bytes in 1 blocks
==6858==   total heap usage: 384 allocs, 383 frees, 88,684 bytes allocated
==6858==
==6858== 568 bytes in 1 blocks are still reachable in loss record 1 of 1
==6858==    at 0x4C29F73: malloc (vg_replace_malloc.c:309)
==6858==    by 0x578CC4C: __fopen_internal (in /usr/lib64/libc-2.17.so)
==6858==    by 0x40114B: sdds::phoneDir(char const*, char const*) (in /home/kshiman/OOP244/DIY/ws)
==6858==    by 0x40156E: main (in /home/kshiman/OOP244/DIY/ws)
==6858==
==6858== LEAK SUMMARY:
==6858==    definitely lost: 0 bytes in 0 blocks
==6858==    indirectly lost: 0 bytes in 0 blocks
==6858==      possibly lost: 0 bytes in 0 blocks
==6858==    still reachable: 568 bytes in 1 blocks
==6858==         suppressed: 0 bytes in 0 blocks
==6858==
==6858== For lists of detected and suppressed errors, rerun with: -s
==6858== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

这是结构:

    struct record {
        char name[50];
        int prefix;
        int area;
        int number;
    };

这是主文件:

#include "Phone.h"
using namespace std;
using namespace sdds;
#define _CRT_SECURE_NO_WARNINGS
int main() {
if (Name == "!")
    break;
    phoneDir("Star Wars", "phones.txt");
    return 0;
}

这里,

if (Name == "!")
    break;

您正在破坏外循环,因此在不关闭文件的情况下退出代码。这会泄漏内存。您应该在 break.

之前关闭文件