C - realloc导致崩溃

时间:2016-03-10 20:22:55

标签: c crash dynamic-arrays realloc

我试图实现从控制台读取的一个字符串的动态数组(可以是任意长度)。但是它在循环中的realloc()调用时崩溃了。代码:

session_start();

$sessId = 'voi44bhncdt58j5gfssnje37n11';

if(session_id() === $sessId){
    echo "valid php session";
} else{
    echo "invalid php session";
}

崩溃出现在以下输入中:

void kill(char **memory, int count) {
        if (memory != NULL) {
        for (int i = 0; i < count; i++) {
            if (memory[i] != NULL) {
                free(memory[i]);
            }
        }
        free(memory);
    }
}

char **getData(int *strCount, int *allocatedCount) {
    int maxStrCount = 10;
    int maxStrLength = 10;
    char **data = malloc(sizeof(char *) * maxStrCount);
    if (data == NULL) {
        return NULL;
    }
    for (int i = 0; i < maxStrCount; i++) {
        data[i] = malloc(sizeof(char) * maxStrLength);
        if (data[i] == NULL) {
            kill(data, i);
            return NULL;
        }
    }
    int i = 0;
    int j = 0;
    for (char ch = getchar(); ch != EOF; ch = getchar()) {
        if (ch == '\n') { // if end of line
            data[i][j] = '\0';
            i++;
            j = 0;
            if (i >= maxStrCount) {
                // extend array
                char **newData = realloc(data, sizeof(char *) * (maxStrCount * 2));
                if (newData == NULL) {
                    kill(data, maxStrCount);
                    return NULL;
                }
                maxStrCount *= 2;
                data = newData;
                for (int k = i; k < maxStrCount; k++) {
                    data[k] = malloc(sizeof(char) * maxStrLength);
                    if (data[k] == NULL) {
                        kill(data, k);
                        return NULL;
                    }
                }
            }
        } else { // if not end of line
            data[i][j] = ch;
            j++;
            if (j >= maxStrLength - 1) { // extend string
                maxStrLength *= 2;
                char *newStr = realloc(data[i], sizeof(char) * maxStrLength); // Here it crashes
                if (newStr == NULL) {
                    kill(data, maxStrCount);
                    return NULL;
                }
                data[i] = newStr;
            }
        }
    }
    if (j > 0) { // in case of file doesn't end with empty line
        data[i][j] = '\0';
        i++;
    }
    if (i == 0) { // in case of empty input
        kill(data, maxStrCount);
        return NULL;
    }
    *strCount = i;
    *allocatedCount = maxStrCount;
    return data;
}

它是这样的:它读取&#34; Lorem ips&#34;,然后调用realloc,然后读取&#34; Lorem ipsum dolor s&#34;,然后再次调用realloc,一切正常。然后它读取&#34; amet,consectetur&#34; (第2行)和&#34; adipiscing elit,sed do eiusmod tempor&#34; (第3行),然后尝试重新分配和崩溃。

我看着所有这些尝试调试,但我仍然不知道它为什么会崩溃。

1 个答案:

答案 0 :(得分:2)

您正在所有字符串之间共享变量maxStrLength

您正在重新分配第2行的缓冲区并增加maxStrLength;但是,当你正在阅读下一行时,它的缓冲区较小,所以你在这里写入了它的界限:

data[i][j] = ch;