[英]struct definition inside main() causing Segmentation Fault
是不可能在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,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;
}
}
不知道为什么会这样。 我正在使用Solaris SunStudio编译器。
在第一个示例中, suite
位于堆栈中,而第二个示例则位于数据段上。
由于suite
非常大(约75MB),因此segfault几乎可以肯定是由于程序耗尽了堆栈空间。
在大多数情况下,最好在堆上分配大型数据结构(使用malloc()
等)。 这也可以只分配您需要的空间量,而不是总是为500个元素分配空间。
在main中声明一个结构是可以的。 但是在你的程序中,问题与你在main函数中创建500个该结构对象的事实有关。 每个对象的大小约为15 KB。 因此,500个对象需要大约75 MB。 试试printf("size: %lu\\n", sizeof suite);
。
默认情况下,您没有那么多堆栈可用。 您可以使用命令ulimit -s
找到可用的堆栈。 它以KB为单位打印可用堆栈。
您可以使用ulimit
命令增加堆栈。 例如ulimit -s 100000
。
更好的方法是使用malloc()
动态分配所需的内存。
定义struct
并在任何函数(包括main
声明该struct
的局部变量是合法的。
但是代码在语法上可能是合法的并且在运行时崩溃(例如,因为它具有未定义的行为,根据C标准,或者因为它遇到某些系统限制,例如对调用堆栈的限制)。
您在main之外定义的结构是全局的和未初始化的,因此它将进入.bss段并在执行开始时初始化为0。 你在main中定义的结构是巨大的,超过了最大堆栈大小(在Linux上也可能是Solaris大约1-2MB)。 由于main之外的那个不在堆栈上,它似乎在那种情况下工作而不是另一个。
除了有关堆栈空间,malloc和未定义行为的答案。 。 。
当我尝试编译你的代码时,我得到了3个警告。
test.c:7:6: warning: return type of ‘main’ is not ‘int’
test.c: In function ‘main’:
test.c:32:17: warning: implicit declaration of function ‘strcpy’
test.c:32:17: warning: incompatible implicit declaration of built-in function ‘strcpy’
为main返回一个int,而不是void。
int main(int argc,char **argv)
在C中,strcpy的头是string.h,而不是strings.h。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.