Reputation: 53
This is a function that returns the binary format of decimal as a char *.
char* getbinnumbydec(unsigned int a)
{
char * s;
unsigned int ost = 0;//remainder of the division variable
bool loop = true;
s = (char *)malloc(1);
while(loop)
{
if(a<=1)
loop = false;
ost = a%2;//remainder of the division
a = a/2;
s = (char*)realloc(s, 2);
if(ost == 0)
{
strcat(s, "0 ");
}
else
{
strcat(s, "1 ");
}
}
reverse(s, 0, strlen(s)-1);
strcat(s, "\0");
return s;
//returns for example 1 0 1 0 (with space separator)
//if 10 (decimal) was transfered to this function
And it works. But if I pass a number greater than 8191 to this function, then an error message is displayed:
*** Error in `./bin': realloc(): invalid next size: 0x0000000000f67010 ***
Aborted
Can someone help me to solve it?
Upvotes: 1
Views: 51
Reputation: 182855
First problem:
The strcat
function requires a string as its first parameter. But the first time you call strcat
, s
may or may not contain a string. You need a *s = 0;
after the first malloc
for s
.
Second problem:
Your first time through the loop, you reallocate to two bytes. Then you try to copy "0 " in. But it would take three bytes to hold that string ('0', ' ' and the terminating zero byte). So you haven't allocated enough space.
Third problem:
strcat(s, "\0");
The strcat
function requires a string as its first parameter. A string, by definition, terminates with a zero byte. So this serves no purpose. To know where to put the zero byte, it would have to search for the existing zero byte, so one would have to already be there or this would be illegal.
Upvotes: 1