SegFault при переключении с небольшого тестового файла на файл размером 31 Мб

Ниже мой (неполный) код для проекта сортировки слиянием. Это работало хорошо для частей, которые я реализовал, пока я не переключился с тестового файла на 128 строк на файл размером 31 Мб, который должен быть отсортирован. Теперь получаю segfault, и я не уверен, что делать, чтобы решить эту проблему.

Удалены некоторые строки, которые я считаю несущественными, потому что "в основном код".

struct Record {
    char key[KEYSIZE+1];
    char data[DATASIZE+1];
};
int threadCount;
int tiers;
static struct ThdArg {
        int thdNum; // Thread number 0,1,2,3
        struct Record * lowRec; // First record of group or first index of record
        struct Record * hiRec;  // Last record of group or last index of record   
};


int lines;
int tiers;
void *threadFunc(void *var)
{
    struct ThdArg temp2 = *((struct ThdArg*)var);
    qsort((temp2.lowRec), lines/threadCount, sizeof(struct Record), comparator);
    for(int k=0;k<tiers;k++)
        if(temp2.thdNum%(int)(pow(2,k+1))==0)
        {
            qsort((temp2.lowRec), lines/(threadCount/(int)pow(2,k+1)), sizeof(struct Record),comparator);   

        }
}

int main(int argc, char **argv[])
{
    if (argc!=2)
    {
        printf("Please enter a file name");
        return 0;
    }
    threadCount =8;

    tiers =(int)log2((double)threadCount);
    pthread_t threads[threadCount];
    FILE *recordFile=fopen(argv[1], "r");
    char ch;
    fseek(recordFile, 0, SEEK_END);
    lines = ftell(recordFile);
    fseek(recordFile, 0, SEEK_SET);
    lines=lines/64;

    struct Record recArr[lines]; 

    char  buffer[9];
    char buffer2[57];
    for(int j=0;j<lines;j++)
    {
        fgets(buffer, 9, recordFile);
        for(int i=0;i<8;i++)
        {
            recArr[j].key[i]=buffer[i];
        }
        recArr[j].key[8]='\0';
        fgets(buffer2, 57, recordFile);
        for(int i=0;i<56;i++)
        {
            recArr[j].data[i]=buffer2[i];
        }
        recArr[j].data[57]='\0';
    }
    struct ThdArg temp[threadCount];
    for(int i=0;i<threadCount;i++)
    {
        temp[i].thdNum = i;
        temp[i].lowRec=&recArr[(lines/threadCount)*i];
        temp[i].hiRec=&recArr[(lines/threadCount)*(i+1)-1];
        pthread_create(&threads[i],NULL, threadFunc, (void *)&temp[i]);
    }
    for(int i=0;i<threadCount;i++)
    {
        pthread_join(threads[i], NULL);
    } 

}

1 ответ

Решение

Следующая строка:

struct Record recArr[lines]; 

выделяет память в стеке. Его размер ограничен. Если вы читаете файл, который может быть очень большим, используйте malloc:

#include <stdlib.h>

typedef struct  {
    char key[KEYSIZE +1];
    char data[DATASIZE +1];
}Record;

...

recArr = malloc(sizeof(Record) * lines);
...
free(recArr);

Вы можете использовать указатель как массив. (На самом деле они одинаковые)

Другие вопросы по тегам