简体   繁体   English

将内存分配给3维char数组会导致分段错误

[英]Allocating memory to a 3-dimensional char array causes segmentation fault

As a spin of of an earlier question, I have run into some problems regarding allocating memory to a 3 dimensional array. 作为先前问题的一个转折点,我遇到了一些有关将内存分配给3维数组的问题。

I am working on a project where we need to do some work on a text. 我正在做一个需要在文本上做一些工作的项目。 To do this, we need to split the text into smaller sections, and process the text word for word. 为此,我们需要将文本分成较小的部分,然后逐字处理文本。 To save these smaller pieces of text, we have a 3D array, a list of sections each containing a list of the words in the section. 为了保存这些较小的文本,我们有一个3D数组,一个节列表,每个节包含节中单词的列表。

But I get a segmentation fault when I try to allocate memory for the individual words using malloc() . 但是,当我尝试使用malloc()为单个单词分配内存时,出现了段错误。

localText->list[i][n] = malloc(100 * sizeof(char));

Here is the entire code. 这是完整的代码。

typedef struct {
   char name[100];
   char  ***list;
}text;

int main(){
   int i = 0, n, z,wordCount, sections;
   FILE *file;
   text *localText;

   openFile(&file, "test.txt");
   wordCount = countWords(file);

   sections = (wordCount / 50) + 1;

   localText = malloc(sizeof(text));
   localText->list = malloc(sections * sizeof(char **));

   for(i = 0; i < sections; i++)
      localText->list[i] = malloc(50 * sizeof(char *));
      for(n = 0; n < 50; n++)
         localText->list[i][n] = malloc(100 * sizeof(char));

   readFileContent(file, localText->list, 50);

   freeText(localText);

   return 1;
}

You're missing some braces: 您缺少一些括号:

for(i = 0; i < sections; i++) {
// ...
}

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

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