在 codeblocks 16.01 运行 会出现如题的问题,然而在古老的VC6里居然没问题
代码如下 就是 4个结构体链成链,输出内容
#include
#include
#include
#define true 1
#define false 0
int i=0;
typedef int Boolen;
typedef struct Node1
{
char Text;
Boolen Sign;
Node1 Next;
Node1* Part;
}*InText;
int TextCompare(InText a)
{
if(strcmp(a->Text,"&")==0) return 1;
else if(strcmp(a->Text,"|")==0) return 2;
else if(strcmp(a->Text,"<->")==0) return 3;
else if(strcmp(a->Text,"->")==0) return 4;
else if(strcmp(a->Text,"over")==0||strcmp(a->Text,"flag")==0) return 5;
else return 6;
}
int OutputText(InText it)
{
InText p1=NULL;
p1=it;
if(p1==NULL) return -1;
if(strcmp(p1->Text,"")==0)
p1=p1->Next;
while(p1!=NULL){
if(p1->Sign==false)
printf("!");
/* if(TextCompare(p1)==5){
printf("(");
OutputText(p1->Part);
printf(")");
}else /
if(TextCompare(p1)==4)
printf("->");
else{
printf("%s",p1->Text);
}
p1=p1->Next;
}
//printf("\n");
return 1;
}
int main()
{
InText head=(InText)malloc(sizeof(InText));
head->Sign=true;
head->Next=NULL;
head->Part=NULL;
head->Text=(char)malloc(10*sizeof(char));
head->Text[0]='\0';
strcat(head->Text,"b");
InText head1=(InText)malloc(sizeof(InText));
head1->Sign=true;
head1->Next=head;
head1->Part=NULL;
head1->Text=(char*)malloc(10*sizeof(char));
head1->Text[0]='\0';
strcat(head1->Text,"->");
InText head2=(InText)malloc(sizeof(InText));
head2->Sign=true;
head2->Next=head1;
head2->Part=NULL;
head2->Text=(char*)malloc(10*sizeof(char));
head2->Text[0]='\0';
strcat(head2->Text,"a");
InText head3=(InText)malloc(sizeof(InText));
head3->Sign=true;
head3->Next=head2;
head3->Part=NULL;
head3->Text=(char*)malloc(10*sizeof(char));
head3->Text[0]='\0';
OutputText(head3);
printf("\n");
}
你需要了解C/C++的基础概念:指针和内存分配。
你的程序问题在于你分配内存的时候写错了。
InText head=(InText)malloc(sizeof(InText));
在这里,InText是一个Node1结构的指针,sizeof(InText)的大小是指针的大小(32位系统下为4字节)。
你只分配了指针大小的内存,却要访问超过这个大小的数据内容,当然会出错了。
正确的分配方式是: InText head=(InText)malloc(sizeof(Node1));
关键问题就在这里,你自己再调试一下就可以解决了。
另外,head->Text=(char)malloc(10*sizeof(char));
这里也是不对的,Text是一个char类型,并非指针,不能这么分配。
调试到最后就是输出结果
codeblocks里调试,正常出结果 输出 a->b ; 然而直接运行就崩溃。在vc6里怎么弄都没事。这是IDE的问题?
codeblocks在一个函数中连续分配多个内存时容易崩溃。我也遇到过,不是代码的问题。