【发布时间】:2018-02-19 23:02:46
【问题描述】:
我正在制作一个程序,它从文件中读取文本,将其分隔为字母数字单词,等等。我遇到了一个问题,我已经从文件中读取到一个字符串,并且我试图将该字符串分隔为一个二维数组,其中每个单词都存储在一个数组中。从那里我将继续订购它们。
但是,当我 malloc for words[n] 时,我遇到了段错误。对于我正在使用的测试文件,它有大约 400 个字符。单词的长度不会超过 10 个字符,因此 (j - i + 1) 不会是可能导致堆栈溢出的巨大分配(除非我误解了我的分配)。
如果需要,我可以解释我的函数代码,这是对我编写的 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;
}
}
值得注意的是,文件输入有效,并且分隔算法有效(它正确地捕获了文件中从 i 到 j 的第一个单词)。我需要 malloc 来获取 ** 字词吗?我不认为这是问题所在,但我不知道示例文件中有多少字,所以我必须 malloc 大量。
【问题讨论】:
标签: c segmentation-fault malloc pointer-to-pointer