1

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 i.e. fscanf(fid, "%d", &fIndex); in the first iteration itself i.e. 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 ....

e.g.

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

1 回答 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.

于 2013-10-30T15:33:55.373 回答