구조체 정의를 내 main()일으키는 세분화류
문제
그것은 가능하지 않을 정의 구조 안에 main().나는 다음만을 얻을 수 Segmentation Fault:
#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는 스택 공간이 부족한 프로그램으로 인해 SegFault가 거의 확실합니다.
대부분의 경우 힙에 큰 데이터 구조를 할당하는 것이 가장 좋습니다 (malloc()
et al을 사용하여).이렇게하면 500 요소의 공간을 항상 할당하는 대신 필요한 공간을 할당 할 수 있습니다.
다른 팁
그것은 좋아요를 선언 구조 내의 주요.하지만,프로그램에서 문제가 사실과 함께 만들고 있는 500 개체의 구조 내에 주요 기능입니다.각 객체에 대한 15KB 크기에 있습니다.그래서,500 개 요구에 대해 75MB 입니다.도 printf("size: %lu\n", sizeof suite);
.
당신 없는 의 스택은 기본적으로 사용할 수 있습니다.당신을 찾을 수 있습니다 사용할 스택을 사용하여 명령 ulimit -s
.그것을 인쇄 사용 가능한 스택에서 KBs.
사용할 수 있습니다 ulimit
명령을 증가합니다.예: ulimit -s 100000
.
더 나은 방법을 동적으로 할당하는 메모리를 사용하여 필요 malloc()
.
그것은 법적을 정의할 struct
과 지역 변수를 선언하면 그 struct
안에 어떤 기능을 포함하여, main
.
하지만 코드를 수 있는 구문으로 법률 충돌에서 런타임(예:을 가지고 있기 때문에 정의되지 않은 행동이 따 C 표준,기 때문에 또는 숙박 시스템의 일부 제한 사항,같은 제한 호출 스택에).
메인 외부에서 정의한 구조체는 글로벌이며 초기화되지 않으므로 .BSS 세그먼트로 이동하여 실행이 시작될 때 0으로 초기화됩니다.메인 내부를 정의한 구조체는 거대하고 최대 스택 크기 (Linux에서 약 1-2MB 및 Solaris도 약 1-2MB)를 초과합니다.메인 외부가 스택에 있지 않으므로 다른 경우에는 작동하는 것처럼 보입니다.
스택 공간, 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’
.
int가 void가 아니라 int를 반환합니다.
int main(int argc,char **argv)
.
c에서 strcpy의 헤더는 string.h, strings.h가 아닙니다.