realloc():char*变量的下一个大小无效
这是一个将十进制的二进制格式作为字符*返回的函数realloc():char*变量的下一个大小无效,c,malloc,realloc,C,Malloc,Realloc,这是一个将十进制的二进制格式作为字符*返回的函数 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 =
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
有人能帮我解决吗?第一个问题:
strcat
函数需要一个字符串作为其第一个参数。但是第一次调用strcat时,s
可能包含也可能不包含字符串。您需要一个*s=0对于s
,在第一个malloc
之后的code>
第二个问题:
strcat(s, "\0");
第一次通过循环时,重新分配到两个字节。然后尝试在中复制“0”。但是需要三个字节才能保存该字符串(“0”、“0”和终止的零字节)。所以你没有分配足够的空间
第三个问题:
strcat(s, "\0");
strcat
函数需要一个字符串作为其第一个参数。根据定义,字符串以零字节结尾。所以这是没有用的。要知道将零字节放在哪里,它必须搜索现有的零字节,因此必须有一个零字节已经存在,否则这将是非法的。你能给我们足够的代码来编译和运行以复制错误吗?在某种程度上,你让所有的realloc
变得不必要的复杂和低效。您必须检查您的体系结构,但可能unsigned int
是4字节,32位。您希望每4位有一个空格,因此最多7个空格,加上一个NUL终止符,总共是40字节。内存很便宜,只需分配您所需的最多内存即可。例如,100就足以实现可移植性。