繁体   English   中英

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

[英]c - why does a pointer to a struct crash the program?

所以问题是该程序在标记的位置崩溃。 最有趣的是,一切都可以在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)); 

分配不足,因为BigDecimal是一个隐藏指针的typedef 永远不要这样做!

应该只是:

new = malloc(sizeof *new);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM