我在Main中调用它时在打印功能中有一个未知的segfault,我看不到明显的修复程序是什么。我在整个程序中都放置了printf,它没有打印" shere4",这使我认为这是由于我的打印功能,或者当我以main命名时。
我想将字典文件读为一系列字符串。
这是代码的片段:
任何想法都将不胜感激,谢谢。
#define PRIME 1009
void fileRead(int argc, char **argv)
void printTable(int arrayLength, char **table);
int main(int argc, char **argv)
{
char **table;
FILE *fp;
int i, arrayLength = PRIME;
/* Initial memory allocation */
table = (char**)malloc(PRIME*sizeof(char));
fileRead(argc, argv);
printf("here3n");
for(i = 0; i < arrayLength; i++) {
printTable(arrayLength,table);
}
printf("here4n");
return 0;
}
void fileRead(int argc, char **argv)
{
FILE *fp;
char *word;
int arrayLength = PRIME;
word = calloc(MAXCHAR, sizeof(char));
fp = fopen (argv[1], "r");
printf("here1n");
/*read in grid and move along a cell each time */
while (fscanf(fp, "%s", word)!= EOF) {
if (argc != (2)) {
fprintf(stderr, "Cannot open file, %sn Try again e.g. %s dictionary.txtn" , argv[1], argv[0]);
}
if(fp == NULL) {
fprintf(stderr, "Cannot open file, %sn Try again e.g. %s dictionary.txtn" , argv[1], argv[0]);
return;
}
if (fp == NULL) {
fprintf(stderr, "Error opening file, try file name dictionary.txtn");
exit(EXIT_FAILURE);
}
}
printf("here2n");
fclose(fp);
return;
}
void printTable(int arrayLength, char **table)
{
int i;
for(i = 0; i < arrayLength; i++) {
printf("%sn", table[i]);
}
printf("n");
}
让我总结您的代码:
- 您为
table
分配非初始化的内存 - 您调用功能
fileRead()
:- 为
word
分配一些内存 - 阅读文件
- 对读取的数据无能为力。
-
fileRead()
没有任何有用的东西:它不会返回任何东西,它不触摸table
,容易受到word
的缓冲溢出,并将word
的内存泄漏留在后面。
- 为
- 然后您
printf
table
尝试此
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PRIME 1009
#define MAXCHAR 256
char **fileRead(FILE *fp, int *len);
void printTable(int arrayLength, char **table);
int main(int argc, char **argv){
if (argc != 2) {
fprintf(stderr, "Need dictionary file argument.nTry again e.g. %s dictionary.txtn" , argv[0]);
exit(EXIT_FAILURE);
}
FILE *fp = fopen (argv[1], "r");
if(fp == NULL) {
fprintf(stderr, "Cannot open file, %snTry again e.g. %s dictionary.txtn" , argv[1], argv[0]);
exit(EXIT_FAILURE);
}
int arrayLength = PRIME;
char **table = fileRead(fp, &arrayLength);//fclose(fp) inside this
printTable(arrayLength, table);
for(int i = 0; i < arrayLength; ++i)
free(table[i]);
free(table);
return 0;
}
char **fileRead(FILE *fp, int *len){
char *word = calloc(MAXCHAR, sizeof(char));
char **table = malloc(*len * sizeof(char*));
int i = 0;
while (i < *len && fscanf(fp, "%s", word) != EOF){
table[i] = malloc(strlen(word)+1);
strcpy(table[i++], word);
}
fclose(fp);
*len = i;
free(word);
return table;
}
void printTable(int arrayLength, char **table){
int i;
for(i = 0; i < arrayLength; i++) {
printf("%sn", table[i]);
}
printf("n");
}