简体   繁体   中英

Pointers in C++; segmentation fault error:

I have just started to study C++, and right now I am working with pointers. I cannot understand why the following thing is happening.

So, say I have two classes A and B. A has an integer field (int valueA) and B has a pointer field (to A), A *a. Below I have shown both classes.

class A{
   A::A(int value){
    valueA = value;
}


 void A::displayInfo (){
      cout<<A<<endl;
    }
 }



class B{

    B::B(){
    a=0;
  }


  void B::printInfo (){
       a -> displayInfo(); //Segmentation fault
     }

  void B::process(){
     A new_A = A(5);
     a = &new_A;
     new_A.displayInfo(); //correct output
     a -> displayInfo();  //correct output
     }
  }

Now when in my main class I do the following: create an instance of the B class and call the process() and print() functions. In the output I get: 5(which is correct), 5(which is correct) and Segmentation fault. Can anyone please help me understand why this is happening? According to my current understanding of pointers, I am doing the correct thing?

int main(void) {

B b_object();
b_object.process();
b_object.print();

}


Just to make this clear, I have an Ah and Bh file where I declare "int valueA;" and "A *a;" respectively. And I know this can be done much easier without pointers, but I am trying to learn how pointers work here :D

 A new_A = A(5);
 a = &new_A;

Here you create new_A which is local to process and assign its address to a . When the process function ends, new_A goes out of scope and is destroyed. Now a points at an invalid object.

The real solution here is to not use pointers like this, but if you really have to, to have something last beyond the end of the function you need to dynamically allocate it. Do this with a = new A(5); . You need to make sure that you delete a; at some later point in the program, otherwise the dynamically allocated memory will be leaked.

a被分配给process()中的局部变量,因此在printInfo()中无效

变量a在您的方法中是本地的-在类级别声明它

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM