简体   繁体   中英

Exc_bad_access Error in fscanf

I'm running the following code in Xcode setup for iOS project and get the EXC_BAD_ACCESS (code=2, address 0x30) on the second fscanf command ie fscanf(fid, "%d", &fIndex); in the first iteration itself ie with j = 0 ;

char word[wordLength]; // wordlength is set to 4
int numFiles = 0;
int fIndex = 0;
// create the word-fileIndex mapping
for(long i = 0; i < numWords; i++)
{
    fscanf(fid, "%s%d", word, &numFiles);
    vector<int> indexList(numFiles,0);
    for(int j = 0; j < numFiles; j++)
    {
        fscanf(fid, "%d", &fIndex);
        indexList[j] = fIndex;
    }
    wordIndexMap[word] = indexList;
}

However, just for the sake of testing, I added another value to be scanned in the first fscanf like this:

fscanf(fid, "%s%d%d", word, &numFiles, &fIndex);

And it ran fine and read the correct value from the file.

Can someone enlighten me with what is going on here?

My input file is like this:

abcd num_Index index1 index2 ....

eg

1234 2 14 15
1235 3 5 2 6
1111 1 1

I think you should set wordLength to more than 4 because you need to include the trailing '\\0' . In any case, you need to be careful when reading input like that and limit how many characters you're reading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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