获取浮点异常(核心转储)。我不知道如何解决它

时间:2015-04-13 23:34:56

标签: c++ c

在键功能中给出错误。至少是gdb所说的。在此先感谢。

#include <stdio.h>
#include <stdlib.h>
#include <iostream>   // for cin and cout in C++
#include <cassert>    // for assert
#include <strings.h>
#include <string.h>
#include<time.h>
using namespace std;

int lcombinations=0;
int distinct=0;

线性哈希函数。

void linear(char *tword, int key, int n, char **lcArray)
{
int c;
while(c==0)
{
    if(key==n)
    {
        key=0;
    }
    if(strlen(lcArray[key])==0)
    {
        lcArray[key]=tword;
        c=1;
    }
    else
    {
        key++;
        lcombinations++;
    }
}   
}

生成散列函数的密钥

void key(char *tword, int l, int n, char **lcArray)
{
int total=0;
int k;
for(int i=0; i<l; i++)
{
    total= total+tword[i];
}
total=n%total;
k=rand()%25+66;
total=total*k;
linear(tword, total, n, lcArray);
}

int counter=0;

找到测试中的所有不同单词。

void distinct_words(char *tword, char **distinct, int l, int n, char **lcArray)
{
int j;
int k=0;
if(counter==0)
{
    counter++;
    distinct[0]=tword;
    key(tword,l,n,lcArray);
}
else
{
    for(j=0; j<counter; j++)
    {
        if(strcmp(distinct[j],tword)!=0)
        {
            k++;
        }
    }
    if(k==counter)
    {
        distinct[counter]=tword;
        counter++;
        key(tword,l, n, lcArray);
    }
}

}

接收并将文本分成单词

int main()
{
srand(time(NULL));
FILE *inFile;
char word[81];
char *tword;
inFile = fopen("will.txt", "r");    // Open for reading, hence the "r"
assert( inFile);            // make sure file open was OK
int i=0;
int n=65437;
int j,k;
char **distinct= (char **)malloc(sizeof(char **)*n);
char **lcArray= (char **) malloc(sizeof(char*)*n);
for(int p=0; p<n; p++)
{
    lcArray[p]= (char *) malloc(sizeof(char)*81);
}
while(fscanf(inFile, "%s",word) != EOF)
{
    i++;
    k= strlen(word);
    tword= (char *)malloc(sizeof(char)*k);
    int l=0;
    for(j=0; j<k; j++)
    {
        if(isalnum(word[j]))
        {
            word[j]=toupper(word[j]);
            tword[l]=word[j];
            l++;
        }
    }
    printf("%s ", tword);
    distinct_words(tword, distinct, l, n, lcArray);
}

}

1 个答案:

答案 0 :(得分:2)

我怀疑你的浮点异常是由这一行产生的:

total=n%total;

...具体来说,如果total为零,则可能导致许多系统上出现浮点异常。

您可以通过防止模数值为零的可能性来避免异常:

if (total != 0)
{
   total=n%total;
}
else 
{
   printf("Hey, modulo by zero is undefined!  (It's similar to divide-by-zero!)\n");
   total = 0;  // or something
}

顺便说一句,您需要学习的一件关键事项 - 如果您想在编程时保持理智 - 是如何准确追踪代码中发生崩溃的位置。您可以使用调试器(通过单步执行代码执行和/或通过设置断点)来执行此操作,或者您可以通过喷洒临时printf()来推断崩溃发生的位置(或者类似的)在整个代码中,以便您可以看到在崩溃之前打印的内容,并使用它来缩小问题位置。任何一种技术都可行,当只是眼睛看到代码并没有给你答案时,通常需要一种技巧。