C ++ Segmentation故障测试代码昨天工作完善现在它出错了

时间:2014-04-03 18:31:13

标签: c++ segmentation-fault

截至目前的程序计算了ASCII代码中每个字符的出现次数。昨天进行测试时,即使是我尝过的最大案例(小说中的哈克芬恩)也没有任何错误。我今天加载它并再次测试它,它给我一个分段错误。我没有更改或添加任何代码。这是昨天完美运作的相同代码。我不明白它将如何工作,而不是下一天。运行调试器时,我得到了这个:

    Program received signal SIGSEGV, Segmentation fault.
    0x00007ffff7343f01 in getc () from /lib64/libc.so.6

我的代码:

#include <cstdio>

using namespace std;

//==============================================================
//                  initialize
//==============================================================
// initialize(freq) initializes all values in the array pointed
// to by freq to 0.
//==============================================================
void initialize(int* freq)
{
   for(int i = 0; i<=256; i++)
   {
      freq[i]=0;
   } 
}

//==============================================================
//                  getFreq
//==============================================================
// getFreq(inf, freq) counts the number of occurences of each
// character in file inf and stores those numbers into the array
// freq at with the index number being the ASCII code for that 
// character
//==============================================================

void getFreq(FILE* inf, int* freq)
{
   int c = fgetc(inf);
   while(c != EOF)
   {
      freq[c]++;
      c = fgetc(inf);
   }  

}

//==============================================================
//                  showCount
//==============================================================
// showCount(freq) prints the counts of the characters stored in
// freq at with the indexs being the ASCII code for each charater.
// *Does not print characters that do not occur
//==============================================================

void showCount(int* freq)
{
   for(int i = 0; i <= 256; i++)
   {
      if(freq[i]> 0)
      {
         if(i == ' ')
         {
            printf("Spaces: %i \n", freq[i]);
         }
         else if(i == '\n')
         {
            printf("Newlines: %i \n", freq[i]);
         }
         else if(i == '\t')
         {
            printf("Tabs: %i \n", freq[i]);
         }
         else if(i == '.')
         {
            printf("Periods: %i \n", freq[i]);
         }
         else
         {
            printf("%c's: %i \n",i , freq[i]);
         }
      }
   }
}

int main(int argc, char* argv[])
{
   int* freq = new int[256];
   initialize(freq);
   FILE* inf = fopen(argv[1], "r");
   getFreq(inf, freq);
   showCount(freq);
   fclose(inf);
}​

2 个答案:

答案 0 :(得分:4)

当数组实际上只有256个元素从索引0到索引255时,你在代码中使用i&lt; = 256.代码显示未定义的行为。昨天工作得很好,今天在我的屁股上咬我是一个完美的例子,说明当代码展示UB时会发生什么。

答案 1 :(得分:1)

您不是通过访问数组外部的元素(数组的索引256从0到255)来检查fopen的返回值并超越缓冲区。