动态创建2d数组并复制txt文件。分段错误

时间:2015-03-31 13:21:36

标签: c

我一直在为此代码获取分段错误。任何建议如何解决?我知道我想在每个malloc()之后使用free(),但是在我返回创建的数组时,我不知道我的函数是怎样的。奇怪的是,这段代码可以在家里工作,但不是在学校,我必须让它工作。任何建议都将受到高度赞赏。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void changeToLower(const char *regular, char *lowerCaseOnly)
{
    size_t ctr;
    size_t len = strlen(regular);
    int i=0;
    while(i<len) 
    {
        lowerCaseOnly[i] = tolower((unsigned char) regular[i]); 
        i++;    
    }
    lowerCaseOnly[len] = '\0';
}
char ** enterFile(int *size, char * nameofFile )
{
    int l;
    int ne;
    int messageSize         =165;
    char fname[40]          ;//="dictionary2.txt";
    FILE *file              =NULL;
    int i                   ;
    char **dArray           =NULL;
    int localsize           =0;
    if(strcmp(fname, "quit\n") == 0){
        exit(-1);
    }
    printf("Enter the name of the dictionary file you'd to use: ");
    fgets(fname,100, stdin);
    strtok(fname, "\n"); 
    strcpy(nameofFile,fname);
    file = fopen(fname,"r");
    if(file==NULL){ printf("Error could not find file;\n");}//In case file DNE
    fscanf(file, "%d", size);       
    localsize=(*(size)*2)+1;
    *size=localsize;
    //Allocation of memory for 2D array
    dArray =  malloc(localsize*sizeof( char*)); 
    for(i=0;i<localsize;i++){
        dArray[i]=malloc(messageSize*sizeof(char));
    }
    i=0;
    while(!feof(file))
    {
        fgets(dArray[i],messageSize, file);
        strtok(dArray[i], "\n");
        i++;
    }   
    fclose(file);
    printf("Dictionary File Loaded\n");
    return dArray;    
}
int main()
{
    int size              =0;
    int ne, counter         ;
    char **dArray      =NULL;                   //pointer to array  DOUBLE ARRAY
    char option             ;
    int x                 =1;                                       //Neede DND
    char nameofDictionary[40]=" ";
    while(x!=5)
    {
        printf("|------------------------------------------------------|\n");
        printf("| Enter Option 1: To open dictionary file              |\n");
        scanf(" %c", & option);
        while((ne=getchar()) != '\n' && ne!= EOF );//====> DELETE
        //printf("You entered this option:\t %c\n", option);
        switch(option)
        {
        case '1':
            dArray=enterFile(&size, nameofDictionary);     
            //  printf("main file name now is: %s\n", nameofDictionary);
            break;
        case '2':
            //option2(dArray, &size);
            break;
        case '3':   
            //option3(dArray, &size);
            break;
        case '4':
            //dArray=option4(dArray,&size, nameofDictionary);
            //  printf("this should say futbol %s",dArray[151]);
            break;
        case '5':
            x=5;
            printf("Exit program.");
            break;
        default:
            printf(">>>>INVALID: Enter a valid input, try again\n");
        }
    }
    return 0;
}

enter image description here

TEXTFILE只包含以下句子:

75
nevermind
nvm
not much
nm
no problem
np
people
ppl
talk to you later
ttyl
because
cuz
i don't know
idk
as soon as possible
asap
yeah
ya
how are you
hru
you
u
are
r
late
l8
at
@
good morning
gud morn
see you later
c u l8r
hello
lo
love
<3
as far as i know
afaik
away from keyboard
afk
thanks
thx
today
2day
before
b4
great
gr8
at the moment
atm
by the way
btw
oh my gosh
omg
rolling on the floor laughing
rofl
if i remember correctly
iirc
message
msg
please
plz
for your information
fyi
in my opinion
imo
just kidding
jk
you only live once
yolo
today
2day
tomorrow
2moro
tonight
2nite
alright
aight
also known as
aka
ask me anything
ama
with
w/
without
w/o
be right back
brb
on my way
omw
busy
bz
can
cn
cool
coo
disconnected
d/c
definitely
def
them
dem
too long; didn't read
tl;dr
estimated time of arrival
eta
favorite
fav
facebook
fb
got to go
g2g
good game
gg
good job
gj
congratulations
gratz
what
wat
i don't care
idc
i know, right
ikr
whatever
meh
minutes
mins
real life
rl
skater
sk8r
seriously
srsly
sorry
sry
whats up
sup
to be determined
tbd
throwback thursday
tbt
too much information
tmi
text
txt
thank you
ty
what the freak
wtf

1 个答案:

答案 0 :(得分:2)

您的代码遗憾地缺少许多地方的错误检查。由于缺少错误检查,有一个特定的地方你可能会失败:

i=0;
while(!feof(file))
{
    fgets(dArray[i],messageSize, file);
    strtok(dArray[i], "\n");
    i++;
} 

这不会检查以确保您将i限制为dArray的大小,因此您可以轻松地在此处超出范围,例如如果文件中的行数超出预期。您可能希望将循环更改为:

i=0;
while (i < localSize && fgets(dArray[i], messageSize, file))
{
    strtok(dArray[i], "\n");
    i++;
} 

检查代码的其余部分是否存在其他类似问题,其中缺少错误检查可能会导致不良事件发生。守卫守卫!