简体   繁体   English

malloc上的双指针分段错误

[英]Segmentation fault on malloc for double pointer

I'm making a program that reads in text from a file, delimits it into alphanumerical words, and so on. 我正在编写一个程序,该程序从文件中读取文本,将其分隔为字母数字单词,依此类推。 I'm running into an issue where, I've read from the file into a string, and I'm trying to delimit that string into a 2d array where each word is stored in an array. 我遇到了一个问题,在该问题中,我已经从文件中读取了一个字符串,然后尝试将该字符串定界为一个二维数组,其中每个单词都存储在一个数组中。 From there I will go on to order them. 从那里,我将继续订购它们。

However, I am getting a segfault when I malloc for words[n]. 但是,当我为单词[n]分配内存时,出现了段错误。 For a test file that I'm using, it has ~400 characters. 对于我正在使用的测试文件,它具有约400个字符。 No word is longer than say 10 characters, so (j - i + 1) wouldn't be a huge allocation that might cause a stack overflow (unless I'm misunderstanding my allocation). 没有一个单词的长度超过10个字符,因此(j-i + 1)不会是一个很大的分配,它可能导致堆栈溢出(除非我误解了我的分配)。

I can explain my code for the function if need be, it's a manipulation of a strsplit() function that I wrote. 我可以根据需要解释该函数的代码,它是对我编写的strsplit()函数的操纵。

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

int main(int argc, char** argv) {
    if (argc != 2) {
        printf("Please provide 1 argument.\n");
        return 0;
    }

    FILE *file = fopen(argv[1], "r");
    fseek(file, 0, SEEK_END);
    size_t length = ftell(file); // Getting file size

    char buff, **words, buffer[length + 1];
    int i = 0, j = 0, n = 0, h = 0;

    buffer[length] = '\0';
    rewind(file);
    fread(buffer, 1, length, file); // Read file into buffer, close file
    fclose(file);

    // Deliminate to 2-D array of words
    while (buffer[i] != '\0') {
        while (isalnum(buffer[j]))
            j++;
        i = j;
        while (isalnum(buffer[j]))
            j++;

        words[n] = (char *)malloc(sizeof(char) * (j - i + 1));
        while (i < j)
            words[n][h++] = buffer[i++];

        n += 1, h = 0;
    }
}

It's worth noting that the file input works, and the algorithm to delimit works (it correctly captures the first word from the file from i to j). 值得注意的是,文件输入有效,并且定界算法有效(它正确地捕获了文件中从i到j的第一个单词)。 Do I need to malloc for **words? 我需要为** word分配malloc吗? I don't think that's the issue, but I wouldn't know how many words are in a sample file so I would have to malloc some large amount. 我不认为这是问题所在,但是我不知道示例文件中有多少个单词,因此我将不得不分配大量的单词。

You never actually set the value of words to anything. 您从未真正将words的值设置为任何值。 words needs some memory before you can populate words[n] . words需要一些记忆才能填充words[n]

You could do char** words = malloc(MAX_NUM_OF_WORDS * sizeof(char*)) or have a stack based collection: char* words[MAX_NUM_OF_WORDS] 您可以执行char** words = malloc(MAX_NUM_OF_WORDS * sizeof(char*))或具有基于堆栈的集合: char* words[MAX_NUM_OF_WORDS]

Free tip for the day: using file without a NULL check is not good practice. 今天的免费提示:使用没有NULL检查的file不是一个好习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM