函数调用中的分段错误

时间:2015-03-30 04:38:28

标签: c++

所以我已经让我的程序达到了编译的程度,但是在调用其他函数时,程序会因为Segmentation Fault(核心转储)错误而丢失。 一切都有效。我会添加整个代码以防设置错误(可能因为我不特别理解指针或传递值等)

#include <cmath>
#include <iostream>
using namespace std;

void discrim0(float a, float b, float c, float * root1, float * root2);
void discrimmore(float a, float b, float c, float * root1, float * root2);
void discrimless(float a, float b, float c, float * real, float * sqrtim);

int main()
{

 float discrim;
 float a;
 float b;
 float c;
 float * root1=0;
 float * root2=0;
 float * real=0;
 float * sqrtim=0;
 char cAgain;

 cout << "Welcome to the quadratic roots calculator." <<endl;

 do
 {
  do
  {

   cout << "Please enter the three coefficient values of the" <<endl;
   cout << "quadratic equation. The coefficient of x^2 must not"<<endl;
   cout << "be 0." <<endl;

   cin >> a >> b >> c;

   if(a==0)
   {
    cout << "The value you entered for the coefficient of x^2"<<endl;
    cout << "is not valid(0). Please enter a proper value."<<endl;
   }
  }while(a==0);


  discrim=(b*b)-4*a*c;

  if(discrim<0)
   {
    cout << "Your equation has two imaginary roots."<<endl;
    //error occurs here
    discrimless(a,b,c, real, sqrtim);
    cout << *real << " + " << *sqrtim << "i" << endl;
    cout << "and" << endl;
    cout << *real << " - " << *sqrtim << "i" << endl;
   }

   if(discrim==0)
   {
    cout << "Your equation two roots of the same value."<<endl;
    //error occurs here
    discrim0(a,b,c, root1, root2);
    cout << *root1 << " and " << *root2 << endl;
   }

   if(discrim>=0)
   {
    cout << "Your equation has two real roots, which are: "<<endl;
    //error occurs here
    discrimmore(a,b,c, root1, root2);
    cout << *root1 << " and " << *root2;
   }

   cout << "Would you like to run another calculation? Y/y/N/n"<<endl;
   cin >> cAgain;

  }while(cAgain=='Y'||cAgain=='y');

  return 0;
 }

 void discrim0(float a, float b, float c, float * root1, float * root2)
 {
  *root1= ((-b + sqrt((b*b)-4*a*c))/2*a);

  *root2= ((-b - sqrt((b*b)-4*a*c))/2*a);
 }

 void discrimless(float a, float b, float c, float * real, float * sqrtim)
 {
  *real= (-b)/(2*a);
  *sqrtim= (sqrt(-(b*b-4*a*c)))/(2*a);

 }

 void discrimmore(float a, float b, float c, float *  root1, float * root2)
 {
  *root1= ((-b + sqrt((b*b)-4*a*c))/2*a);

  *root2=((-b - sqrt((b*b)-4*a*c))/2*a);
 }

我在代码中标记了它发生的位置。基本上它会告诉你根的数量,然后崩溃。我理解seg故障的一般概念,我试图访问我没有或没有这种效果的记忆,但我不知道它为什么会发生。另外请记住,我不太懂技术说得太好。谢谢。

2 个答案:

答案 0 :(得分:1)

float * root1=0;
float * root2=0;
float * real=0;
float * sqrtim=0;

您正在声明四个指针并且您永远不会为它们分配有效的内存地址。

答案 1 :(得分:1)

你的问题是你在宣布指针

float * root1=0;
float * root2=0;
float * real=0;
float * sqrtim=0;

并将它们传递给各种函数,而不指向有效的内存。

查看您拥有的函数,您不需要声明指针。您需要使用object并在函数调用中传递这些对象的地址。

float root1=0;  // Good to initialize them.
float root2=0;
float real=0;
float sqrtim=0;

他们用语法调用函数:

discrim0(a,b,c, &root1, &root2);

discrimmorediscrimless的调用进行类似的更改。