2012-05-29 92 views
0

我試圖寫一個簡單的程序,將數字轉換爲單詞(即它將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; 
} 
+1

這看起來像一個家庭作業問題。如果是這樣,你應該用作業標籤標記它。另外,有沒有什麼理由爲你'#include '然後用'char *'作爲你的字符串?最後,'const char * place []'可能不會達到你期望的效果。 – OmnipotentEntity

+0

@OmnipotentEntity謝謝。這不是一個家庭作業問題,我只是試圖學習使用遞歸已知問題的內存管理。 –

回答

2

「可以在任何一個點出如果執行時下面的代碼可能有內存泄漏?」

是的,它可以。

char *temp_string = new char[100]; // first assignment 

[...] 

if (number>=1000) 
{ 
[...] 
    temp_string = convert_number(number,places); 

當您以這種方式重新分配temp_string時,第一個分配的內存變得不可訪問,並且它還沒有被釋放。首先你應該delete[]

+0

感謝您的評論。我剛開始使用C++並試圖學習內存管理。我用'char * temp_string;'改變了'char * temp_string = new char [100];'並刪除了'delete [] temp_string'語句,程序運行時沒有任何錯誤。這是否解決了所有問題? –

+0

你用變量'string'和'word'做同樣的事情,你是否也改變了這些?此外,僅供參考,您可以使用Valgrind自動檢查這些事情。 – OmnipotentEntity

+0

我用'string'做了同樣的事情,但用'word'嘗試過同樣的事情,它給我一個總線錯誤。 我會嘗試Valgrind,謝謝他的信息。 我想了解這些指針如何在函數調用創建堆棧時如何工作以及如何使用函數返回來釋放它。 –