【问题标题】:Trouble dynamically allocating memory for string array无法为字符串数组动态分配内存
【发布时间】:2017-03-28 20:12:10
【问题描述】:

我正在尝试编写一个函数来读取文本文件并将文本文件的每一行复制到传递给函数的数组的一行中。

void read_lines(FILE* fp, char*** lines, int* num_lines) {  
    int i = 0, line_count = 0;
    char line[256], c;

    fscanf(fp, "%c", &c);
    while(!feof(fp)){
        if(c == '\n') {
            ++line_count;
        }
        printf("%c", c);
        fscanf(fp, "%c", &c);
    }

    rewind(fp);
    *num_lines = line_count;

    lines = (char***)malloc(line_count * sizeof(char**));
    while (fgets(line, sizeof(line), fp) != NULL) {
        lines[i] = (char**)malloc(strlen(line) * sizeof(char*));
            strcpy(*lines[i], line);
        }
        ++i;
    }
}

初始部分扫描换行符,以便我知道最初分配给行的数量。我不确定我哪里出错了。

此外,如果有人有任何资源可以帮助我更好地理解如何动态分配空间,那将不胜感激。

【问题讨论】:

标签: c memory segmentation-fault


【解决方案1】:

您应该了解指针的工作原理。在那之后,动态内存分配任务将非常简单。现在你的代码完全错误:

//here you assign to the argument. While this is technically allowed 
//it is most certainly not what you have intended
lines = (char***)malloc(line_count * sizeof(char**));
while (fgets(line, sizeof(line), fp) != NULL) {
        //sizeof(char*) <> sizeof(char).  Also you need a space for the trailing \0 
        lines[i] = (char**)malloc(strlen(line) * sizeof(char*));
        //[] precedes * so it is copying the string somewhere you not intend to
        strcpy(*lines[i], line);
    }
    ++i;
}

正确的版本应该是:

*lines = malloc(line_count * sizeof(char*));
while (fgets(line, sizeof(line), fp) != NULL) {
    (*lines)[i] = malloc((strlen(line) + 1) * sizeof(char));
    strcpy((*lines)[i], line);
    }
    ++i;
}

注意,您需要使用(*lines)[i] 构造,因为[] 运算符在*(取消引用)运算符之前。

【讨论】:

    【解决方案2】:

    代码正在犯各种错误,包括@Ari0nhh 详述的关键错误

    另一个是计数'\n'fgets() 相比,可能无法通过 3 种方式获得正确的行数:

    1. 行超过 256。

    2. 超过INT_MAX 行。

    3. 最后一行不以'\n' 结尾。

    建议改为使用 same 循环来计算“行数”

    unsigned long long line_count = 0;
    while (fgets(line, sizeof(line), fp) != NULL) {
        line_count++;
    }
    
    rewind(fp);
    
    .... 
    
    assert(line_count <= SIZE_MAX/sizeof *(*lines));
    *lines = malloc(sizeof *(*lines) * line_count);
    

    【讨论】:

      猜你喜欢
      • 2018-06-16
      • 2013-06-07
      • 1970-01-01
      • 1970-01-01
      • 2017-12-10
      • 2016-03-25
      • 2020-11-28
      • 2020-04-13
      • 1970-01-01
      相关资源
      最近更新 更多