读书人

realloc有关问题还是那有有关问题呢

发布时间: 2012-02-04 15:43:08 作者: rapoo

realloc问题还是那有问题呢
/*
*字符串长度
*/
int strLength(char *str){
int i=0;
while(*str!= '\0 '){
i++;
str++;
}
return i;
}
/*
*字符串连接
*/
void strCat(char *to,char *from){
int a,b,i=0,j=0;
a=strLength(to);
b=strLength(from);
to = realloc(to,a+b+1);
while(from[j]!= '\0 '){
to[a+j]=from[j];
j++;
}
to[a+b]= '\0 ';

puts(to);
}
void main(){
char *ss= "dsfksdfdsf ";
char *des= "weeldflasdfldf ";
strCat(ss,des);
}
可以出正确结果,但是运行结束后,下面多一行Null pointer assignment。
怎么回事呀?turobc2.0下通过。

[解决办法]
realloc(to,a+b+1);的第一个参数必须是malloc/alloc出来的,因为它在分配更大内存的时候会对第一个参数调用delete
[解决办法]
realloc的是对malloc返回的指针进行操作,即指向堆上内存空间的指针
ss是一个指针字符串的指针,不能这样操作

读书人网 >C语言

热点推荐