程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程解疑 >> vc6-C/C++ debug調試沒問題 直接運行崩潰

vc6-C/C++ debug調試沒問題 直接運行崩潰

編輯:編程解疑
C/C++ debug調試沒問題 直接運行崩潰

在 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類型,並非指針,不能這麼分配。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved