現在、一部のテキストを処理する必要があるプロジェクトで作業しています。これを行うには、テキストを小さなセクションに分割する必要があります。mallocの問題が原因でセグメンテーションフォルトが発生する
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct paragraph{
char **words;
}paragraph;
typedef struct text{
char name[100];
paragraph *list;
}text;
void readFileContent(FILE *file, paragraph *pa, int size){
char localString[100];
pa->words = (char **)malloc(size * sizeof(char *));
int i = 0, z;
while(fscanf(file, "%s", localString) == 1 && i < size){
z = strlen(localString);
pa->words[i] = (char *)malloc(z + 1);
strcpy(pa->words[i], localString);
i++;
}
}
void main(){
int i = 0, n, z;
FILE *file;
text *localText;
localText = (text *)malloc(sizeof(text));
openFile(&file, "test.txt");
i = countWords(file);
i = i/50 + 1; // calculate the number of section need for the text
localText->list = calloc(sizeof(paragraph *), i);
for(n = 0; n < i ; n++){
printf("Paragraph - %d\n", n);
readFileContent(file, &localText->list[i], 50);
}
for(n = 0; n < i ; n++){
printf("Paragraph - %d", n);
for(z = 0; z < 50; z++){
printf("no. %d\n", z);
printf("%s\n", localText->list[n].words[z]);
}
}
}
私がプログラムを実行しようとすると、下の印刷ループにセグメント違反が発生します。私はそれがメモリを割り当てることにいくつかの問題が原因だと思うが、私は理由を理解することはできません。
アップデート1 私は、テキストセグメントを格納するための3次元配列を使用するコードを変更しましたが、私はmalloc関数を使用してメモリを割り当てるしようとすると、私はまだセグメンテーションフォールトを取得します。
localText->list[i][n] = malloc(100 * sizeof(char));
彼女は変更されたコードです。
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;
}
デバッガでプログラムを実行する必要があります。クラッシュすると、変数の値を調べることができます。 –
for(i = 0; i
@BlagovestBuyukliev:おそらく根ですここのエラーの原因。配列の束縛に 'i'を使うのは悪い考えです。 – thiton