Сбой Realloc после второго звонка - PullRequest
0 голосов
/ 29 апреля 2018

Я пытаюсь прочитать список слов, которые нужно отсортировать, и я начинаю с довольно небольшого массива (10 элементов), а затем хотел бы увеличить размер массива на 10, если текущая емкость не соответствует довольно. Кажется, это работает с первым realloc, но я получаю SIGABRT при попытке снова вызвать realloc. Я уверен, что это простая вещь, которую я не вижу, но я не могу понять это. Вот моя программа:

int main(int argc, char *argv[]){
    char *string = malloc(100);
    // Array of pointers starting with 100 elements
    char **toSort = malloc(100*sizeof(char *));
    if(toSort == NULL) {
        exit(1);
    }

    for(int i = 0; i < 100; i++) {
        // Each string can be up to 100 characters long
        toSort[i] = malloc(101);
        if(toSort[i] == NULL) {
            exit(1);
        }
    }

    // Get all lines in the file
    int counter = 0;
    int max = 10;
    char *toAdd;


    FILE *txt = fopen("wlist0.txt", "r");


    while(fgets ( string, 100, txt ) && counter < max) {;

        toAdd = malloc(100);
        if(toAdd == NULL) {
            exit(1);
        }
        strcpy(toAdd, string);

        toSort[counter] = string;
        counter++;

         //if the array needs to be enlarged
        if(counter == max) {
            char **new = realloc(toSort, (max+10) * sizeof(char));
            if(new == NULL) {
                exit(1);
            }
            for(int i = max; i < max + 10; i++) {
                toSort[i] = malloc(101);
                if(toSort[i] == NULL) {
                    exit(1);
                }
            }
            toSort = new;
            max += 10;
        }
    };

    for(int i = 0; i < max; i++) {
        char *word = toSort[i];
        printf("%s", word);
    }

    for(int i = 0; i < max; i++) {
       free(toSort[i]);
    }

    free(toSort);


    return 0;
};

Как говорят мои комментарии, максимальная длина моих строк составляет 100 символов. Я полагаю, что мог бы также динамически распределять память для строк, но я буду беспокоиться об этом, когда у меня будет работать другой realloc. Любая помощь будет принята с благодарностью.

1 Ответ

0 голосов
/ 29 апреля 2018

Этот код присваивает значения toSort после того, как память, на которую он указывает, освобождается / изменяется realloc():

     //if the array needs to be enlarged
    if(counter == max) {
        char **new = realloc(toSort, (max+10) * sizeof(char));
        if(new == NULL) {
            exit(1);
        }
        for(int i = max; i < max + 10; i++) {
            toSort[i] = malloc(101);  <--- toSort is invalid here
            if(toSort[i] == NULL) {
                exit(1);
            }
        }
        toSort = new;
        max += 10;
    }

Это будет работать лучше:

     //if the array needs to be enlarged
    if(counter == max) {
        char **new = realloc(toSort, (max+10) * sizeof( *new )); <-- fixed here, too
        if(new == NULL) {
            exit(1);
        }
        toSort = new;
        for(int i = max; i < max + 10; i++) {
            toSort[i] = malloc(101);
            if(toSort[i] == NULL) {
                exit(1);
            }
        }
        max += 10;
    }

В вашем коде могут быть другие ошибки. Я не полностью изучил это.

...