C++ 使用动态内存时可能存在内存泄漏?

C++ 使用动态内存时可能存在内存泄漏?,c++,memory-leaks,dynamic-memory-allocation,C++,Memory Leaks,Dynamic Memory Allocation,在这个程序中,我编码得到一个名称列表,特别是使用指针,并对列表执行冒泡排序和二进制搜索。我知道有更好的方法来处理这种类型的记忆,但我想在继续之前正确地学习这种方法。我在未正确释放和/或分配内存时遇到错误,但现在,运行此代码时没有出现任何错误消息,尽管我仍然认为某些内存未正确释放。这是我的密码: Main.cpp #include "Functions.h" void main() { // initialize variables int numNames = 0;

在这个程序中,我编码得到一个名称列表,特别是使用指针,并对列表执行冒泡排序和二进制搜索。我知道有更好的方法来处理这种类型的记忆,但我想在继续之前正确地学习这种方法。我在未正确释放和/或分配内存时遇到错误,但现在,运行此代码时没有出现任何错误消息,尽管我仍然认为某些内存未正确释放。这是我的密码:

Main.cpp

#include "Functions.h"
void main() {
     // initialize variables
     int numNames = 0;
     char* search;
     int index = 0;
     bool isSearching = true;
     // get list of names
     cout << "Enter your list of names:" << endl;
     char** nameList = readList(numNames);
     // sort list of names
     bubbleSort(nameList, numNames);
     // show sorted list of names
     cout << "Sorted list of names:" << endl;
     for (int i = 0; i < numNames; i++) {
         cout << nameList[i] << endl;
     }
     // do binary search loop
     do {
         // get search word
         cout << "Enter a word you would like to search for: " << endl;
         search = readLine();
         // get index of search
         index = binarySearch(nameList, numNames, search);
         // if missing
         if (index == -1) {
             cout << "That word is missing" << endl;
         }
         // show index
         else {
            cout << "That word is at index " << index << endl;
         }
         // set loop test
         isSearching = search[0] != '\0';
         // free mem
        delete[] search;
     } while (isSearching);
     // free mem
     for (int i = 0; i < numNames; i++) {
        delete[] nameList[i];
     }
     delete[] nameList;
     system("Pause");
}
ReadFunctions.h

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

#include "ReadFunctions.h"
#include "SortingAndSearchingFunctions.h"

#endif
#ifndef READ_FUNCTIONS_H
#define READ_FUNCTIONS_H

#include <iostream>
#include <conio.h>
#include <memory.h>
#include "Functions.h"

using namespace std;

char* readLine();
char** readList(int &);

#endif
#ifndef SORTING_AND_SEARCHING_FUNCTIONS_H
#define SORTING_AND_SEARCHING_FUNCTIONS_H

#include "Functions.h"
#include <string.h>

void bubbleSort(char** &, int);
int binarySearch(char** &, int, char*);

#endif

是什么阻止您使用
std::vector
std::string
?这将消除所有内存泄漏,提高代码的效率,并大大减少代码的大小。使用
std::sort
还有助于降低代码不必要的复杂性

//可能需要delete语句?
注释周围确实需要delete[]语句

您修改的代码不起作用,因为:

if (numWords >= maxWords) {
    maxWords += firstNumWords;
    temp = new char*[maxWords];
    for (int i = 0; i < numWords; i++) {       // you're copying into uninititialized pointers !!!!!
        memcpy(temp[i], wordList[i], (strlen(wordList[i]) + 1) * sizeof(char));
    }
    for (int i = 0; i < numWords; i++) {
        delete[] wordList[i];
    }
    wordList = temp; 
}

这是一个类的赋值,要求使用指针,没有我们还没有讨论过的库。你是说temp变量需要delete语句吗?这意味着必须循环通过双指针来删除所有内容。没有,因为你复制了包含的指针,但需要删除已使用的单词列表。我修改了上面的代码,并在0xCDCDCD中获得了访问冲突错误。我是不是删除不正确、复制内存不正确还是其他原因?我的老师不允许我们使用swap,你能告诉我一个不使用该函数的方法吗?首先,是什么让你认为你有内存泄漏?当我在上面修改的readList函数中使用带有temp双指针变量的新语句时,没有任何内容被删除。但是,当我修改它时,弹出一条错误消息,指出0xCDCDCD中存在访问冲突。IIRC调用
delete
时出现访问冲突可能意味着您已经对该变量使用了
delete
。存在,因此您必须仔细设计代码,以免意外删除已删除的变量,或者在删除变量后为其赋值
null
,然后在调用
delete
之前始终检查它是否为null。
#include "SortingAndSearchingFunctions.h"

static bool isAfter(char* str1, char* str2) { // check if first string is after the second string
    // initialize variables
    bool isGreater = false;
    bool isEqual = false;
    char c1;
    char c2;
    int compareLen = (strlen(str1) >= strlen(str2)) ? strlen(str2) : strlen(str1);
    // check c-strings
    for (int i = 0; i < compareLen; i++) {
        // get compare characters
        c1 = str1[i];
        c2 = str2[i];
        // check if both alphabetical
        if (((c1 >= 'a' && c1 <= 'z') || (c1 >= 'A' && c1 <= 'Z')) && ((c2 >= 'a' && c2 <= 'z') || (c2 >= 'A' && c2 <= 'Z'))) {
            // normalize for case insensitive
            if (c1 >= 'A' && c1 <= 'Z') {
                c1 = (char)(c1 + 32);
            }
            else if (c2 >= 'A' && c2 <= 'Z') {
                c2 = (char)(c2 + 32);
            }
        }
        // handle comes after
        if (c1 > c2) {
            isGreater = true;
            isEqual = false;
            i = compareLen;
        }
        // handle comes before
        else if (c1 < c2) {
            isGreater = false;
            isEqual = false;
            i = compareLen;
        }
        // handle equal
        else {
            isEqual = true;
        }
        // case with symbol, which case to compare with?
    }
    // handle equal comparison region
    if (isEqual) {
        if (strlen(str1) > strlen(str2)) {
            isGreater = true;
        }
    }
    return isGreater;
}

void bubbleSort(char** & wordList, int numWords) { // bubble sort for word lists
    // initialize variables
    char* temp;
    bool swap = false;
    // sort loop
    do {
        // set swap and numwords
        swap = false;
        numWords--;
        // check list
        for (int i = 0; i < numWords; i++) {
            // swap
            if (isAfter(wordList[i], wordList[i + 1])) {
                swap = true;
                temp = new char[((strlen(wordList[i]) >= strlen(wordList[i + 1])) ? strlen(wordList[i + 1]) : strlen(wordList[i])) + 1];
                memcpy(temp, wordList[i], strlen(wordList[i]) + 1);
                //temp = wordList[i];
                memcpy(wordList[i], wordList[i + 1], strlen(wordList[i + 1]) + 1);
                //wordList[i] = wordList[i + 1];
                memcpy(wordList[i + 1], temp, strlen(temp) + 1);
                //wordList[i + 1] = temp;
                //delete[] temp; // if included shows access violation, but should still include and find another way? 
            }
        }
    } while (swap);
}

int binarySearch(char** & wordList, int numWords, char* search) { // binary search for word lists
    // initialize variables
    int first = 0;
    int mid;
    int last = numWords - 1;
    // search loop
    do {
        // set middle index
        mid = (first + last) / 2;
        // check if equal
        if (strcmp(search, wordList[mid]) == 0) {
            return mid;
        }
        // check if after
        else if (isAfter(search, wordList[mid])) {
            first = mid + 1;
        }
        // check if before
        else {
            last = mid - 1;
        }
    } while (first <= last);
    // not found
    return -1;
}
// add word
    wordList[numWords++] = word;
    // expand list
    if (numWords >= maxWords) {
        maxWords += firstNumWords;
        temp = new char*[maxWords];
        memcpy(temp, wordList, numWords * sizeof(char*));
        delete[] wordList;
        wordList = temp; 
    }
if (numWords >= maxWords) {
    maxWords += firstNumWords;
    temp = new char*[maxWords];
    for (int i = 0; i < numWords; i++) {       // you're copying into uninititialized pointers !!!!!
        memcpy(temp[i], wordList[i], (strlen(wordList[i]) + 1) * sizeof(char));
    }
    for (int i = 0; i < numWords; i++) {
        delete[] wordList[i];
    }
    wordList = temp; 
}
if (numWords >= maxWords) {
    temp = new char*[maxWords + firstNumWords];        // allocate new array
    memcpy(temp, wordList, maxWords * sizeof(char*));  // copy the pointer values.
    char* p = wordList;
    wordList = temp;                                   // put new array in place.
    delete[] p;                                        // delete old array.
    maxWords += firstNumWords;                         // fix size var.
}