1

我正在尝试编写一个程序,它从文件中读取字母“A、B、C、D、E”,记下这些字符的所有实例,并忽略大于和小于符号之间的任何字符,“< 和>”。尽管文件似乎已正确打开,但 findCommonAnswers() 中的 for 循环似乎访问了受保护或不存在的值。Windows 提供异常代码 c0000005,GNU 调试器告诉我“0xXXXXX 处的堆块已在 0xXXXXX+1 处修改,请求大小为 6”。在每次调试中,数字 6 一直保持不变。代码的当前输出是“-1.#IND”,在以前的版本中,它为除常量“probabilityArrayLength”之外的所有项目返回零。如果有人可以让我了解错误的性质,将不胜感激。这是我的代码:

#include<stdio.h>
#include<stdlib.h>
...
...
int fsize(FILE *fp)
{

    int prev = ftell(fp);
    fseek(fp, 0L, SEEK_END);
    int sz = ftell(fp);
    fseek(fp,prev,SEEK_SET);    
  return sz;
}

double* findCommonAnswerChoices( )
{
  FILE *data;  
  data = fopen( "F:\\COMP_SCI\\APCalculusBCMultipleChoiceResults.txt", "r" );

int bufferSize = fsize( data ), totalAnswers = 0, instanceOfA = 0, instanceOfB = 0,
instanceOfC = 0, instanceOfD = 0, instanceOfE = 0, probabilityArrayLength =6,    bytesRead = 0;
int j = 0 , k;

double probOfA = 0.0, probOfB = 0.0, probOfC = 0.0, probOfD = 0.0, probOfE = 0.0;
double* probabilities = (double*)malloc( probabilityArrayLength*(sizeof(double)) );

char answers[bufferSize];

if( data==NULL )
{
    printf( "%d %s %d \n",bufferSize, " ", sizeof(data) );
    printf( "Not Enough Memory" );

}
else
{
    bytesRead = fread( answers, 0, bufferSize, data );
}


for( j = 0; j<bytesRead; j++ )
{
    if( answers[j]=='<' )
    {
        do
        {
            j++;
        }
        while( answers[j]!='>' );
    }

    switch( answers[j] )
    {

        case 'A':
            instanceOfA++;
            break;

        case 'B':
            instanceOfB++;
            break;

        case 'C':
            instanceOfC++;
            break;

        case 'D':
            instanceOfD++;
            break;

        case 'E':
            instanceOfE++;
            break;

        default:
            break;
    }

}

fclose(data);

totalAnswers = ( instanceOfA+instanceOfB+instanceOfC+instanceOfD+instanceOfE );
probOfA = ( (double)instanceOfA/(double)totalAnswers );
probOfB = ( (double)instanceOfB/(double)totalAnswers );
probOfC = ( (double)instanceOfC/(double)totalAnswers );
probOfD = ( (double)instanceOfD/(double)totalAnswers );
probOfE = ( (double)instanceOfE/(double)totalAnswers );

probabilities[0] = (double)probabilityArrayLength;
probabilities[1] = probOfA;
probabilities[2] = probOfB;
probabilities[3] = probOfC;
probabilities[4] = probOfD;
probabilities[5] = probOfE;

return probabilities;
}

 int main()
 {
double* something = findCommonAnswerChoices();
int size = (int)something[0];
int p;

for( p = 0; p<size; p++  )
{
    printf( "%g \n", something[p] );
}
free( something );
return 0;
 }
4

1 回答 1

2
double* probabilities = (double*)malloc( probabilityArrayLength );

这分配了 6 个字节,不足以存储 6 个双精度。它应该是:

double* probabilities = malloc(probabilityArrayLength*sizeof(double));

您可以省略强制转换,在 C 中您可以将 a 分配void*给任何类型的指针。

您的fsize方法也有一个错误,您正在寻求最后获取文件的长度,但您并没有在之后重新开始使用fseek(fp, SEEK_SET).

于 2013-01-28T14:36:53.713 回答