[英]C++. How can I free memory correctly?
无需使用库函数即可查找和删除字符串中最大单词的书面代码。 一切正常。 但是,当我要释放内存时,结果为负(显示空行)。 如果您取消对内存释放功能的调用,则所有功能都将正常运行,但是会发生内存泄漏。 我如何解决它? 请帮我。
#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] != '\0') 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 ++。 我看到您的目标是从头开始实施所有内容,可能是为了进行练习。 但是即使那样,您的代码也没有正确设计/构建。
除此之外,您的代码中还存在一些错误:
result[words + 1] = nullptr;
必须为result[words] = nullptr;
您需要result[i][t] = '\\0';
在while循环中split
delete text[i]
必须为delete [] text[i]
您不能从words
分配result
指针存储器,然后释放它,然后将其返回以供调用者使用。
removeWord
后半部分至少还有一个错误。 试图了解您要在那里做的工作很乏味。
您可能想从一个简单的任务开始。 您还应该分步进行,并首先独立检查每个功能的正确性,而不先实施所有功能,然后再进行测试。 还要看看用于内存检查的valgrind工具-如果使用Linux。
正确释放内存的方法是使用RAII:
new
和new[]
delete
和delete[]
配对 如果您不是专门使用std::string
和std::vector
等,则出于学习指针的原因,您最终将编写少量类似于string
和vector
和unique_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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.