今天偶然在一个方法中碰到一个特殊情况:
具体如下介绍:
node* sumMe(node* first, node* second){
if(first==NULL||second==NULL) return NULL;
node *one = first,*two =second;
node *p=NULL,*q=NULL;
node *back=NULL,*res=NULL;
int carry_bit = 0;
int remainder = 0;
int big = 1;
int init = 1;
while(one&&two){
one = one->next;
two = two->next;
if(one==NULL){
big = 0;
break;
}
if(two==NULL){
big = 1;
break;
}
}
if(!big){
p = first;
q = second;
}else{
p = second;
q = first;
}
free(one);
free(two);
while(p){
node *nd = new node();
remainder = p->data+q->data+carry_bit;
nd->data = remainder%10;
if(remainder>=10){
carry_bit = 1;
}else{
carry_bit = 0;
}
p = p->next;
q = q->next;
if(init) {
back = res = nd;
init = 0;
continue;
}
back->next = nd;
back = nd;
}
while(carry_bit){
if(q){
printf("\n%d\n",q->data);
remainder = q->data + carry_bit;
node *adds = new node();
adds->data = remainder%10;
if(remainder>=10){
carry_bit = 1;
}else{
carry_bit = 0;
}
q = q->next;
back->next = adds;
back = adds;
printf("p null\n");
}else{
node* add = new node();
add->data = carry_bit;
back->next = add;
back = add;
printf("pp\n");
carry_bit = 0;
}
}
back->next = NULL;
return res;
}
当传入的两个值为:
int sumOne[] = {1,3,2,5};
int sumTwo[] = {2,4,9,4,5};
node *One = init(sumOne,4);
node *Two = init(sumTwo,5);
node *back = sumMe(One,Two);
输出的res链表数据为:3 7 1 0 4;这让我一头雾水,当调试查看内存数据时发现:在第二个循环的时候q指针此时指向的首地址为res的地址,指向数据3,
然后我在第一个while上设置断点发现,q中第五个元素的指针地址和two当时指向的地址相同,当free时由于两个同时指向一个地址,所以还保留着 ,但是数据已经丢失了。
个人认为:当free掉时,系统再次分配给p,q的首地址与one,two的相同。two还保存着剩余的指针数据,当使用free时q和two共同拥有的数据被释放,从而出现意料外的结果。
个人感觉free 或者delete最好放在该函数的最后,或者使指针指向末尾。