读取文件内容时堆块错误

时间:2013-01-28 14:31:57

标签: c heap-memory fread

我正在尝试编写一个程序,从文件中读取字母“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;
 }

1 个答案:

答案 0 :(得分:2)

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

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

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

你可以省略演员表,在C中你可以为任何类型的指针分配一个void*

您的fsize方法也有错误,您正在寻求最终获得文件的长度,但您不会在fseek(fp, SEEK_SET)后寻求重新开始。