2014-04-06 3 views
-1

gauss seidel 프로그램을 코딩 중이며 현재 malloc 사용에 문제가 있습니다.malloc 구현시 세그먼트 오류

도와주세요. 내가 여기에 붙어서 가우스 절단을 반복하지 않았다.

오류는 "세그먼트 오류 (코어 덤프 됨)"라고 표시됩니다. 나는 그것이 무엇을 의미하는지 모른다. 코드를 여러 번 검사했지만 오류를 찾을 수 없습니다.

제가 FSCANF로 사용 된 방법과 다를 수 있습니까?

#include <stdio.h> 
#include <stdlib.h> 

//structure declarations 
struct table2 { 
int k; 
float value; 
int row; 
int col; 
int nextK_row; 
int nextK_col; 
}; 

struct table3 { 
int index; 
int fir; 
int fic; 
}; 


//function prototypes 
void allocate_memory(int num_unknowns, int num_entries, struct table2 *pTable2, struct table3 *pTable3, float *b, FILE* fInput, FILE* fOutput); 

void free_close (FILE* fInput, FILE* fOutput, struct table2 *pTable2, struct table3 *pTable3, float *b); 


int main (int argc, char* argv[]) { 


//variable declarations 
FILE *fInput=NULL; 
FILE *fOutput=NULL; 
struct table2 *pTable2=NULL; 
struct table3 *pTable3=NULL; 
int num_unknowns, num_entries; 
float *b=NULL; 
int i, j, m; 
int count1, count2, count3, count4, l; 



//check if arguments from user is 3, else error 
if (argc!=3) { 
    printf("Error, the number of arguments should be exactly as needed(three).\n"); 
    return 1; 
} 


//open input file 
fInput = fopen(argv[1], "r"); 
//check if input file opened successfully 
if (fInput == NULL) { 
    printf("Error. Input file wasn't opened successfully.\n"); 
    return 1; 
} 

//open output file 
fOutput = fopen(argv[2], "w"); 
//check if output file opened successfully 
if (fOutput == NULL) { 
    printf("Error. Output file wasn't opened successfully.\n"); 
    return 1; 
} 

//scan no. of unknowns from file and check if successful 
count1 = fscanf(fInput, " %d", &num_unknowns); 
if (count1 != 1) { 
    printf("Error, fscanf() did not read number of unknowns successfully.");  
//call function to free memory and close files 
free_close (fInput, fOutput, pTable2, pTable3, b); 
return 1; 
} 


//scan no. of entries from file and check if successful 
count2 = fscanf(fInput, " %d", &num_entries); 
if (count2 != 1) { 
    printf("Error, fscanf() did not read number of entries successfully."); 
//call function to free memory and close files 
free_close (fInput, fOutput, pTable2, pTable3, b); 
return 1; 
} 


//call function to allocate memory 
allocate_memory(num_unknowns, num_entries, pTable2, pTable3, b, fInput, fOutput); 


//loop to read values from Table2 and check if it read successfully 
for(i=1; i<=num_entries; i++) { 
    count3 = fscanf(fInput, " %d %f %d %d %d %d", &(pTable2[i].k), &(pTable2[i].value), &(pTable2[i].row), &(pTable2[i]).col, &(pTable2[i].nextK_row), &(pTable2[i].nextK_col)); 
    if (count3 != 6) { 
     printf("Error, fscanf() did not read table 2 values successfully."); 
//call function to free memory and close files 
     free_close (fInput, fOutput, pTable2, pTable3, b); 
     return 1; 
    } 
} 

//loop to get values from Table3 
for(j=1; j<=num_unknowns; j++) { 
    count4 = fscanf(fInput, " %d %d %d", &(pTable3[j].index), &(pTable3[j].fir), &(pTable3[j].fic)); 
    if (count4 != 3) { 
     printf("Error, fscanf() did not read table3 values successfully."); 
//call function to free memory and close files 
     free_close (fInput, fOutput, pTable2, pTable3, b); 
     return 1; 
    } 
} 

//loop to get constants from file 
for(m=1; m<=num_unknowns ; m++) { 
    l = fscanf(fInput, " %f", &(b[m])); 
    if (l != 1) { 
     printf("Error, fscanf() did not read constant values successfully."); 
//call function to free memory and close files 
     free_close (fInput, fOutput, pTable2, pTable3, b); 
     return 1; 
    } 
} 



//test print 
for(i=1; i<=num_entries; i++) { 
    printf("%d\t", pTable2[i].k); 
    printf("%f\t", pTable2[i].value); 
    printf("%d\t", pTable2[i].row); 
    printf("%d\t", pTable2[i].col); 
    printf("%d\t", pTable2[i].nextK_row); 
    printf("%d\t", pTable2[i].nextK_col); 
} 
printf("\n\n\n"); 
for(j=1; j<=num_unknowns; j++) { 
    printf("%d\t", pTable3[j].index); 
    printf("%d\t", pTable3[j].fir); 
    printf("%d\t", pTable3[j].fic); 
} 
printf("\n\n\n"); 
for(m=1; m<=num_unknowns ; m++) { 
    printf("%f", b[m]); 
    } 
printf("\n\n\n"); 







//call function to free memory and close files 
free_close (fInput, fOutput, pTable2, pTable3, b); 


return 0; 
} 



//function to allocate memory 
void allocate_memory(int num_unknowns, int num_entries, struct table2* pTable2, struct table3* pTable3, float* b, FILE* fInput, FILE* fOutput) { 


//allocate memory for table 2 
pTable2 = (struct table2*) malloc(24*num_entries); 
if (pTable2 == NULL) { 
    printf("Error, memory allocation for table2 failed."); 
//call function to free memory and close files 
    free_close (fInput, fOutput, pTable2, pTable3, b); 
    exit(-1); 
} 

//allocate memory for table 3 
pTable3 = (struct table3*) malloc(12*num_unknowns); 
if (pTable3 == NULL) { 
    printf("Error, memory allocation for table3 failed."); 
//call function to free memory and close files 
    free_close (fInput, fOutput, pTable2, pTable3, b); 
    exit(-1); 
} 

//allocate memory for constants 
b = (float*) malloc(sizeof(float)*num_unknowns); 
if (b == NULL) { 
    printf("Error, memory allocation for matrix B entries failed."); 
//call function to free memory and close files 
    free_close (fInput, fOutput, pTable2, pTable3, b); 
    exit(-1); 
} 

return; 
} 


//function to free allocated memory and close files 

void free_close (FILE* fInput, FILE* fOutput, struct table2 *pTable2, struct table3 *pTable3, float *b) { 

if (fInput != NULL) 
    fclose(fInput); 
if (fOutput != NULL) 
    fclose(fOutput); 

if (pTable2 != NULL) 
    free(pTable2); 
if (pTable3 != NULL) 
    free(pTable3); 
if (b != NULL) 
    free(b); 

return; 
} 
+0

비명을지를 필요가 없습니다. – musicmatze

+2

디버거를 사용하여 프로그램을 실행하면 ** 어디에서 ** 충돌하는지 알려줍니다. –

+1

값으로 전달 된 포인터를 잊지 마세요. 원본에 영향을 미치지 않고 스택에 푸시 된 내용에 대한 포인터를 넣습니다. – BLUEPIXY

답변

0

대신 pTable2 = (struct table2*) malloc(24*num_entries); 왜이 함수를 호출하지 pTable2 = (struct table2*) malloc(sizeof (struct table2)*num_entries);

+0

그래도 시도했지만 세분화 오류가 발생했습니다. 나는 정말로 무엇을해야할지 모르겠다. 문제는 fscanf와 같지만 huhu = ((((어쨌든 고마워요. – user3503204

+0

malloc의 결과를 캐스팅하지 마십시오. –

+0

__DO__ \ __ALWAYS__는 malloc의 반환 값을 캐스팅합니다. 특히 C++로 코드를 컴파일 할 때마다 – Anonymouse

1

:

allocate_memory(num_unknowns, num_entries, pTable2, pTable3, b, fInput, fOutput); 

당신이 값을 기준으로 모든 변수를 전달합니다. 그런 다음 allocate_memory 내부에서 해당 변수의 로컬 복사본을 변경합니다. 이러한 변경 사항은 main()의 변수에 영향을 미치지 않습니다.

pTable2이 여전히 NULL이기 때문에 ptable2[i] 등의 부분 오류가 main()에 있었던 것 같습니다.

이 문제를 해결하려면 변수를 참조로 전달하십시오. 그러나 전체 free_close 설정이 꽤 추합니다. 모든 관련 제어 변수를 struct에 넣는 것이 좋습니다. main()에 코드의 나머지 부분이있는 함수를 호출하면 함수가 끝난 후 main()이 해제 할 수 있습니다.

또한 세분화 오류가 어디에서 발생하는지 파악하는 방법을 배우는 것이 좋습니다. 디버거를 설정하지 않고 지금 배우고 싶지 않은 경우 코드에 출력 명령문 (플러시 포함)을 삽입하고 프로그램을 실행하고 해당 출력이 표시되는지 확인하여 "디버그"할 수 있습니다. 그렇게하면 점차적으로 문제가있는 줄을 좁힐 수 있습니다.

+0

Anonymouse의 대답도 정확하며, 아마도 잘못된 바이트 수를 malloc 할 것입니다 .IDK 왜 당신은 24를 넣는 것이 좋은 생각일까요?이 관용구를 사용하십시오 :'pTable2 = malloc (num_entries * sizeof * pTable2) '. –