2017-12-10 31 views
0

다양한 크기의 무작위 부동 소수점을 사용하여 정렬 알고리즘의 런타임을 테스트하는 프로그램을 만들고 있습니다. 모든 것이 잘 작동합니다. 정렬 알고리즘이 작동하고 실행 시간이 최대 520,010 크기까지 출력되어 프로그램이 중단됩니다.크기가 520010 인 float 배열을 만들면 다른 모든 크기가 적절하게 된 다음 코드가 충돌합니다.

크기 520,000의 플로트 배열이 초기화되면 프로그램이 중단됩니다. 이것은 너무 큰가요?

연구에서 C가 루프 반복 후에 메모리를 없애는 데 문제가있는 것 같지 않습니다. 그래서 여기에 문제가있는 것 같습니까?

void readFromFile() { 
    FILE *myfile; //File to access randomized floats 
    int currentSz = 10; //Size iterator 
    int maxSz = 1000010; // Maximum size to reference in the loop 

    while (currentSz <= maxSz) { 
     // Creates a new array with the current size. 
     float fileArr[currentSz]; // PROGRAM CRASHES HERE (at size of 520,010) 

     //Initializes file path 
     char fileName[200]; 
     fileName[0] = '\0'; 
     strcat(fileName, "C:\\Users\\MatthewC\\Documents\\HonorsProject341\\RandomFloats\\"); 

     // Creates a size string to represent the current array size, and adds sizeStr 
     // to the file path. 
     char sizeStr[50]; 
     sprintf(sizeStr, "%d", currentSz); 
     strcat(sizeStr, "Floats.txt"); 
     strcat(fileName, sizeStr);     

     // Opens the file 
     myfile = fopen(fileName, "r"); 

     int iterator; 

     // Feeds the elements from the file into the created array 
     for (iterator = 0; iterator < currentSz; iterator++) 
      fscanf(myfile, "%f", &fileArr[iterator]); 

     // Sorts the randomized elements, and times the sorting algorithm. 
     clock_t start = clock(), diff; 
     heapSort(fileArr, currentSz); 
     diff = clock() - start; 

     // Converts to milliseconds. 
     int millisec = diff * 1000000/CLOCKS_PER_SEC; 

     printf("size: %d runtime: %d\n", currentSz, millisec); 
     fclose(myfile); 

     // Updates the size. 
     currentSz += 20000; 
    } 
} 
+0

520,000 = 4 * 520,000 바이트의 부동 소수점 값. 배열로 할당 할 때 연속적으로 사용할 수 없습니다. 당신은 malloc을 시도 할 수 있습니다. – Sudhee

답변

2

(아마도) 스택에 할당 될 로컬 변수에 가변 길이 배열을 만듭니다. 스택은 힙 - 제한 크기와 비교하여 컴퓨터가 훨씬 많은 메모리를 사용할 수 있더라도 일부 지점에서 작업이 실패 할 수 있습니다. realloc으로 시도해보십시오. (아마도) 더 많은 메모리에 액세스 할 수 있습니다. 그리고 리턴 값을 확인하십시오 - 만약 그것이 NULL이면, 프로그램은 충분한 메모리를 할당 할 수 없습니다.

float *fileArr = NULL; 
while (currentSz <= maxSz) { 
    char *newFileArr = realloc(fileArr, currentSz * sizeof(float)); 
    if (!newFileArr) { 
     printf("Error allocating %d floats.", currentSz); 
     break; 
    } 
    fileArr = newFileArr; 
    ... 

} 
free(fileArr); 
+0

while 루프가 끝나거나 각 반복이 끝난 후에 fileArr을 해제 할 수 있습니까? –

+0

편집 :이 작업을! 나는 C와 메모리 재 할당에 아직 익숙하지 않아 도움을 주셔서 감사합니다. –

+0

이 코드는 큰 문제가 있습니다. 'realloc'이 실패 할 경우 메모리 누수가 발생합니다. – tilz0R