带有指针和内存泄漏的递归
Recursion with pointer and memory leak
我试图编写一个简单的程序,将数字转换为单词(即它将123转换为一百二十三)。代码完全编译。代码使用指针和递归,在 c++ 的内存管理方面,我总是觉得这很棘手。任何人都可以指出以下代码在执行时是否会有内存泄漏吗?提前谢谢。
#include <iostream>
#include <string>
using namespace std;
char *convert_number(int, int);
const char *tens[]={"","ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
const char *words[]={"zero","one", "two", "three", "four", "five", "six", "seven", "eight", "nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen", "eighteen","ninteen"};
const char *place[]={"","thouands","million","billion","trillion"};
int main(int argc, char **argv)
{
int number,conv_num,places;
places=1;
char *string= new char[1000];
char *temp_string = new char[100];
cout<<"Enter a number:";
cin>>number;
string = convert_number(number,0);
cout<<"The word is :"<<string<<endl;
}
char *convert_number(int number,int places)
{
int divisor;
char *word;
int conv_num;
char *temp_string = new char[100];
word = new char[100];
divisor=10;
if (number>=1000)
{
conv_num = number % 1000;
number = (number-conv_num)/1000;
places++;
temp_string = convert_number(number,places);
word = strcat(word, temp_string);
word = strcat(word, place[places]);
word =strcat(word," ");
}
else
{
conv_num = number;
}
if (conv_num>=100)
{
word =strcat(word,words[conv_num/100]);
word =strcat(word," hundred ");
conv_num=conv_num%100;
}
if(conv_num >=20)
{
word=strcat(word,tens[conv_num/10]);
word =strcat(word," ");
if(conv_num%divisor>=1)
{
word=strcat(word,words[conv_num%divisor]);
word =strcat(word," ");
}
}
if(conv_num<20)
{
word=strcat(word,words[conv_num]);
word =strcat(word," ");
}
delete[] temp_string;
return word;
}
"谁能指出以下代码在执行时是否会有内存泄漏?"
是的,可以。
char *temp_string = new char[100]; // first assignment
[...]
if (number>=1000)
{
[...]
temp_string = convert_number(number,places);
以这种方式重新分配temp_string时,第一个分配中的内存将变得不可访问,并且尚未释放。 你应该先delete[]
这一点。
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 递归无序映射
- TSP递归解的迭代形式
- 如何在Elixir中调用递归函数并行
- 返回递归调用和仅递归调用的区别
- 数组元素打印的递归方法
- 内存泄漏递归传递动态变量
- 内存泄漏可能是由于递归函数造成的
- 递归中C++内存泄漏
- 带有指针和内存泄漏的递归
- 递归中的内存泄漏
- 使用std::unique_ptr的递归函数导致内存泄漏
- 递归会泄漏内存吗?