c - 无法为字符串数组动态分配内存

标签 c memory segmentation-fault

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

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;
    }
}

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

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

最佳答案

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

//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] 构造,因为 [] 运算符在 * (解引用)运算符之前.

关于c - 无法为字符串数组动态分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40601475/

相关文章:

c++ - 如果 main 中有变量,则段错误(核心已转储)?

c - 如何对齐阵列以使其彼此适合?

C 套接字引发错误代码 22,EINVAL - 无效参数

C - 从单链表中删除元素

c - 参数传递问题

java - 试图定位泄漏点! anon 对 pmap 意味着什么?

linux - 如何切换gdb字节输出分组

memory - 现代 GPU 上纹理内存的最大大小是多少?

c++ - 调用派生类的虚函数时出现段错误

C++ STL 队列、引用和段错误