C++.如何正确释放内存

C++. How can I free memory correctly?

本文关键字:内存 释放 何正确 C++      更新时间:2023-10-16

编写的代码,用于在不使用库函数的情况下查找和删除字符串中最大的单词。一切正常。但是当我想释放内存时,结果是负面的(显示一个空行)。如果删除对内存释放函数的调用,则一切将正常工作,但会出现内存泄漏。我该如何解决?请帮助我。

#include <iostream>
using namespace std;
int length(char *text) // string length
{
    char *begin = text;
    while(*text++);
    return text - begin - 1;
}
int size(char **text) // size of two-dimensional array
{
    int i = 0;
    while(text[i]) i++;
    return i;
}
void free_memory(char **text)
{
    for(int i=0; i<size(text); i++)
        delete text[i];
    delete [] text;
}

char **split(char *text, char delim)
{
    int words = 1;
    int len = length(text);
    for(int i=0; i<len; i++)
        if(text[i] == delim) words++;
    char **result = new char*[words + 1];
    int j = 0, t = 0;
    for(int i=0; i<words; i++)
    {
        result[i] = new char[len];
        while(text[j] != delim && text[j] != '') result[i][t++] = text[j++];
        j++;
        t = 0;
    }
    result[words + 1] = nullptr;
    return result;
}
char *strcat(char *source, char *destination)
{
    char *begin = destination;
    while(*destination) destination++;
    *destination++ = ' ';
    while(*source) *destination++ = *source++;
    return begin;
}
char *removeWord(char *in_string)
{
    char **words = split(in_string, ' ');
    int max = length(words[0]);
    int j = 0;
    for(int i=0; i<size(words); i++)
        if(max < length(words[i]))
        {
            max = length(words[i]);
            j = i;
        }
    int index;
    char *result;
    if(!j) index = 1;
    else index = 0;
    result = words[index];
    for(int i=0; i<size(words); i++)
        if(i != j && i != index)
            result = strcat(words[i], result);
    free_memory(words); // I want free memory here
    return result;
}
int main()
{
    char text[] = "audi and volkswagen are the best car";
    cout << removeWord(text) << endl;
    return 0;
}

事实上,这是 C 风格的编程 - 不是C++。我看到你的目标是从头开始实施一切,可能是为了练习。但即便如此,您的代码也没有正确设计/结构化。

除此之外,你的代码中还有几个错误:

  1. result[words + 1] = nullptr;必须result[words] = nullptr;

  2. 您需要在 while 循环后result[i][t] = ''; split

  3. delete text[i]必须delete [] text[i]

  4. 不能从 words 分配给result指针内存,然后释放它,然后返回它以供调用方使用。

  5. removeWord下半年至少还有一个错误。试图了解您在那里尝试做什么会很乏味。

您可能希望从更简单的任务开始。您还应该逐步进行,首先独立检查每个函数的正确性,而不是实现所有功能,然后再进行测试。另请查看用于内存检查的工具 valgrind - 如果您使用 Linux。

正确释放内存的方法是使用 RAII:

  • 仅在构造函数中使用newnew[]
  • 将它们与相应析构函数中的deletedelete[]配对
  • 尽可能使用自动存储持续时间对象

如果你特别不使用std::stringstd::vector等,出于学习指针的原因,你最终会写一些类似于stringvectorunique_ptr的少量类,然后你开始编程,就好像你正在使用std版本一样。

您有两个问题。首先是result被分配给words中的内存位置。其次,您将strcat的结果存储在可能没有足够的空间的words[i]中(请参阅 strcat 文档)。

result = new char[len(in_string)+1]; // +1 for space for null char
// the old loop reversed the word order -- if you want to keep doing
// that, make this a descending loop
for(int i=0; i<size(words); i++)
    if(i != j && i != index)
        strcat(result, words[i]);
free_memory(words);
return result;

这样当你释放words时,结果指向的也是自由的。然后,您需要在main()中释放result

int main()
{
    char text[] = "audi and volkswagen are the best car";
    char * result = removeWord(text);
    cout << result << endl;
    delete[] result;
    return 0;
}