【发布时间】:2020-06-30 04:26:46
【问题描述】:
这是一个将十进制的二进制格式返回为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
而且它有效。但是如果我将一个大于 8191 的数字传递给这个函数,则会显示一条错误消息:
*** Error in `./bin': realloc(): invalid next size: 0x0000000000f67010 ***
Aborted
有人可以帮我解决吗?
【问题讨论】:
-
你能给我们足够的代码来编译和运行来复制错误吗?
-
有点
,你用 reallocs 让这一切变得不必要的复杂和低效。您必须检查您的架构,但unsigned int可能是 4 字节 32 位。您希望每 4 位有一个空格,因此最多有 7 个空格,再加上一个用于 NUL 终止符的空格,总共 40 个字节。内存很便宜,只需分配您可能需要的最多并使用它即可。例如,100 对便携性来说已经绰绰有余了。