我们目前正在研究一个需要处理一些文本的项目,为此,我们需要将文本分成较小的部分。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;
}
您应该在调试器中运行您的程序。当它崩溃时,您将能够检查变量的值。 – 2011-12-15 11:05:06
这是我第一次看到`for(n = 0; n
2011-12-15 11:08:10