c-为什么指向结构的指针会使程序崩溃?

戴尼乌斯·卡沃里奥纳斯

所以问题是该程序在标记的位置崩溃。最有趣的是,一切都可以在linux下完美运行,但是在Windows平台上,它会立即崩溃。有什么想法吗?

 typedef struct BigDecimalTag* BigDecimal;   
     struct BigDecimalTag
        {
            int number;
            struct BigDecimalTag * next;
            struct BigDecimalTag * prev;

        };

        BigDecimal set(char symbol[]){

            if(symbol!=NULL){   

                if(strlen(symbol)>0){   

                    int end=0;  
                    int i=(int)strlen(symbol)-1; 
                    BigDecimal head=(BigDecimal)malloc(sizeof(BigDecimal));

                    if(head==NULL) return NULL;

                    if(symbol[0]=='-'){

                        if(strlen(symbol)>1&&symbol[1]!='0'){ 
                            head->number=negative; 
                            end=1;
                        }

                        else return NULL;
                    }



                    else if(symbol[0]<='9'&&symbol[0]>'0'){ 
                        head->number=positive;              
                    }

                    else if(symbol[0]=='0'&&strlen(symbol)==1){ 
                        head->number=zero;
                    }

                    else {
                        free(head);
                        return NULL;
                    }   

                        BigDecimal new; 
                        BigDecimal tail=head;

                        for(i;i>=end;i--){

                            if(symbol[i]>'9'||symbol[i]<'0'){
                                trash(&head); 
                                return NULL;
                            }

                            else {

                                new=(BigDecimal)malloc(sizeof(BigDecimal)); 
                                if(new==NULL)return NULL;

                                tail->next=new; 
                                **new->prev=tail;** //<-crash point
                                new->number=(int)symbol[i]-48; 
                                tail=new; 

                            }

                        }

                        return head;

                }

                else return NULL;
            }

            else return NULL;
        }
放松

这:

new=(BigDecimal)malloc(sizeof(BigDecimal)); 

分配不足,因为BigDecimaltypedef隐藏指针的a。永远不要这样做!

应该只是:

new = malloc(sizeof *new);

但是我强烈建议删除typedef-hidden指针,这很令人困惑。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章