2011-10-02 58 views
0

我想建立一個程序,它總結了一個大整數C. 所以我準備好了代碼。程序編譯通過mingw和Visual C++編譯器成功傳遞。但是我的運行部分有問題。奇怪的是,當我在Visual Studio中調試程序時沒有問題,但是當我運行它時,Windows顯示程序停止工作。 這是代碼:C str功能和malloc

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <math.h> 
#include <ctype.h> 
#include "sum.h" 

int isNumber(char* number) 
{ 
    int lenght = strlen(number); 
    int i,result = 0; 
    for (i = 0 ; i < lenght ; i++) 
    { 
     if (isdigit(*number++)) 
     { 
      result = 1; 
     } 
     else 
     { 
      result = 0; 
      break; 
     } 
    } 
    return result; 
} 
int cti(char ch) 
{ 
    return ch - '0'; 
} 
char* addZeros(char* number,int lenght) 
{ 
    int num_lenght = strlen(number),size = abs(lenght - num_lenght),i; 
    char* zeros = (char*)malloc(size); 

    strcpy(zeros,""); 
    zeros[size - 1] = '\0'; 
    for (i = 0 ; i < abs(lenght - num_lenght) ; i++) 
    { 
     strcpy(&zeros[i],"0"); 
    } 
    strncat(zeros,number,size); 
    number = (char*)malloc(sizeof(char)*size); 
    strncpy(number,zeros,size); 
    return number; 
} 
char* sum(char* numberOne,char* numberTwo) 
{ 
    if (numberOne == NULL || numberTwo == NULL) 
     return NULL; 
    if (!isNumber(numberOne) || !isNumber(numberTwo)) 
     return NULL; 

    int CF = 0; 
    int lenghtOne = strlen(numberOne),lenghtTwo = strlen(numberTwo); 
    if (lenghtOne == 0 || lenghtTwo == 0) 
     return lenghtOne == 0 ? numberTwo : numberOne; 
    int max = lenghtOne > lenghtTwo? lenghtOne : lenghtTwo,index; 
    char* result = (char*)malloc(max); 
    int res = 0; 
    result[max] = '\0'; 
    if (lenghtOne > lenghtTwo) numberTwo=addZeros(numberTwo,strlen(numberOne)); 
    else if (lenghtOne < lenghtTwo) numberOne = addZeros(numberOne,strlen(numberTwo)); 
    for (index = max - 1 ; index >=0 ; index--) 
    { 
     res = cti(numberOne[index]) + cti(numberTwo[index]); 
     if (((res%10) + CF) > 9) 
     { 
      int num = ((res%10) + CF); 

      result[index] = (char)((int)'0'+num%10); 
      CF = num/10; 
     } 
     else 
     { 
      result[index] = (char)((int)'0'+((res%10) + CF)); 
      CF = res/10; 
     } 
    } 
    return result; 
} 
int main(int argc, char *argv[]) 
{ 
    char* num = "12345678"; 
    char* num2= "2341"; 
    char* result = sum(num,num2); 
    printf("%s\n",result); 
    return 0; 
} 

我認爲這個問題是在某處的指針,但我沒有絕對的把握這一點。誰能幫我?

+3

那麼是什麼問題,你看,當你看到了嗎? – johannes

回答

2

您分配的內存量不足。它不包含用於終止字符串的空字符的空間,並且不考慮諸如「9」+「1」之類的和的結果長度的變化。然後在數組結束後寫入空終止字符。

你應該這樣長的malloc:

char* result = (char*)malloc(max + 2); 
+0

你是對的,但分配的大小必須是最大+ 1 –

+0

@約旦鮑裏索夫:它需要是最大+2。你需要+1的空終止符和另一個+1的情況下,結果的長度大於弦的長度。對於我在答案中給出的例子,「10」將需要3個字符的空間,而兩個輸入字符串的長度均爲1,因此它必須是max + 2。 – tinman

1
result[max] = '\0'; 

這是不正確的,因爲您只爲結果分配了最大字符。我沒有詳細研究邏輯,但是分配最多1個字符可以解決這個問題。