main()内部的struct定义导致Segmentation Fault
发布时间:2020-12-16 10:21:09 所属栏目:百科 来源:网络整理
导读:是不可能在main()中定义结构. 我尝试以下只是为了获得分段错误: #include stdio.h#include unistd.h#include strings.h#define TRUE 1void main(int argc,char **argv){struct test_struct{ char test_name[50]; char summary_desc[200]; char result[50];}
是不可能在main()中定义结构.
我尝试以下只是为了获得分段错误: #include <stdio.h> #include <unistd.h> #include <strings.h> #define TRUE 1 void main(int argc,char **argv) { struct test_struct { char test_name[50]; char summary_desc[200]; char result[50]; }; struct suite_struct { char suite_name[50]; struct test_struct test[500]; int test_count; int passed; int failed; int unresolved; int notrun; }suite[500]; int a,b; for (a=0;a<500;a++) { strcpy(suite[a].suite_name,""); for (b=0;b<500;b++) { strcpy(suite[a].test[b].test_name,""); strcpy(suite[a].test[b].summary_desc,""); strcpy(suite[a].test[b].result,""); } suite[a].test_count=0; suite[a].passed=0; suite[a].failed=0; suite[a].unresolved=0; suite[a].notrun=0; } } 但是当我在其外部采用结构定义时,它的工作原理是: #include <stdio.h> #include <unistd.h> #include <strings.h> #define TRUE 1 struct test_struct { char test_name[50]; char summary_desc[200]; char result[50]; }; struct suite_struct { char suite_name[50]; struct test_struct test[500]; int test_count; int passed; int failed; int unresolved; int notrun; }suite[500]; void main(int argc,char **argv) { int a,""); } suite[a].test_count=0; suite[a].passed=0; suite[a].failed=0; suite[a].unresolved=0; suite[a].notrun=0; } } 不知道为什么会这样. 解决方法
在第一个示例中,套件位于堆栈中,而第二个示例则位于数据段上.
由于套件非常大(约75MB),因此segfault几乎可以肯定是由于程序耗尽了堆栈空间. 在大多数情况下,最好在堆上分配大型数据结构(使用malloc()等).这也可以只分配您需要的空间量,而不是总是为500个元素分配空间. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |