I want to build a program which sum a big integers in C.
So I’m ready with the code. The program compiling pass successfully with mingw and Visual C++ compiler. But I have a problem with the run part. The strange thing is that when I debug the program in Visual Studio there is no problems but when I run it my Windows show that the program stop working.
This is the code :
#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;
}
I think that the problem is somewhere in the pointers but I’m not absolutely sure about this. Can anyone help me?
The amount of memory you are allocating is not sufficient. It does not include space for the null character terminating the string and it does not take into account changes in the length of the result for sums such as “9” + “1”. You are then writing the null terminating character after the end of the array.
You should malloc with the length like this: