Here I'm trying to write a code to find the powers of 2 by manipulating a string. I know this can be done with some built in functions but I'm interested in doing this using string manipulation techniques.
The problem works fine till 276 and then I don't know why my program displays some unwanted characters. I don't understand why this happens exactly from the exponent 76 and before that I get the desired output.
Here is my code. Hope I can find what's going wrong with your help.
CODE:
Note: Here I use 4 functions
int len()
: to find length of string.void add()
: to perform the operation to find power of 2.void rev()
: displays string in reverse order, as its the desired output.int main()
#include <stdio.h>
#include <stdlib.h>
char *a;
int i;
int len()
{
for(i=0;a[i]!='\0';i++);
return i;
}
void rev()
{
printf("\n");
for(i=len();i>=0;i--)
printf("%c",a[i]);
printf("\n-------------------\n");
}
void add()
{
int k,v=0;
for(k=0;k<len();k++)
{
v=2*(((int)a[k])-48);
a[k]=v+48;
}
for(k=0;k<len();k++)
{
if((int)a[k]>57)
{
if(k<(len()-1))
{
a[k+1]+=1;
a[k]=((((int)a[k])-48)%10)+48;
}//in if 1
if(k==len()-1)
{
realloc(a,(len()+1)*sizeof(char));
a[k+1]=49;
a[k]=((((int)a[k])-48)%10)+48;
}//in if 2
}//out if
}//for
}//add
int main()
{
int j;
a=(char *)calloc(1,sizeof(char));
a[0]='1';
for(j=1;j<=81;j++)
{
add();
printf(" %d :\n",j);
rev();
}
scanf("%d",&i);
return 0;
}
I don't understand what's going wrong... does realloc
has a limitation is assigning memory or is it my system's fault?
EDIT:
As @DavidSchwartz suggested I must assign the newly returning pointer starting address to a the variable
a=realloc(a,(len()+1)*sizeof(char));
and I want to how can I effectively detect and avoid over flow.