C中动态数组中的未初始化值

时间:2018-11-30 21:54:29

标签: c multidimensional-array memory-management valgrind

我已经获得了一个需要用C动态2D数组执行的任务,但是我们甚至还没有介绍过指针,因此我有点不知所措。我必须阅读一些文本输入并将其存储在2D数组中,而不限制其大小。 不幸的是,当执行puts()函数有时会打印出一些随机符号时,Valgrind总是向我抛出一个错误,说存在一个未初始化的值。我知道我必须省略一些索引,但是我只是找不到问题的根源。此外,非常感谢所有有关代码质量的建议。

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


#define MULT 3
#define DIV 2


char **read(int *row, int *col) {
    char **input = NULL;
    int row_size = 0;
    int col_size = 0;
    int i = 0;
    int c;

    while ((c = getchar()) != EOF) {
        if (c != '\n') { // skip empty lines

            assert(i < INT_MAX);
            if (i == row_size) { // if not enough row memory, allocate more
                row_size = 1 + row_size * MULT / DIV;
                input = realloc(input, row_size * sizeof *input);
                assert(input != NULL);
            }

            char *line = NULL;
            int j = 0;
            // I need all the rows to be of the same size (see last loop)
            line = malloc(col_size * sizeof *line); 

            // do while, so as to not skip the first character
            do { 
                assert(j < INT_MAX-1);
                if (j == col_size) {
                    col_size = 1 + col_size * MULT / DIV;
                    line = realloc(line, col_size * sizeof *line);
                    assert(line != NULL);
                }
                line[j++] = c;
            } while(((c = getchar()) != '\n') && (c != EOF));

            // zero-terminate the string
            if (j == col_size) {
                ++col_size;
                line = realloc(line, col_size * sizeof *line);
                line[j] = '\0';
            }

            input[i++] = line;
        }
    }
    // Here I give all the lines the same length
    for (int j = 0; j < i; ++j)
        input[j] = realloc(input[j], col_size * sizeof *(input+j));

    *row = i;
    *col = col_size;
    return input;
}


int main(void) {
    int row_size, col_size, i, j;
    char **board = read(&row_size, &col_size);

    // Initialize the remaining elements of each array
    for (i = 0; i < row_size; ++i) {
        j = 0;
        while (board[i][j] != '\0')
            ++j;
        while (j < col_size-1)
            board[i][++j] = ' ';
    }

    for (i = 0; i < row_size; ++i) {
        puts(board[i]);
    }

    for (i = 0; i < row_size; ++i)
        free(board[i]);
    free(board);

    return 0;
}

0 个答案:

没有答案