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
-hidden 指针,这只会造成混淆。
所以问题是这个程序在标记点崩溃了。最有趣的是,在 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
-hidden 指针,这只会造成混淆。