Calling override of virtual function is causing a segmentation fault

Viewed 349

I am trying to override a function but end up with a segmentation fault. I followed some Tutorials and now I'am not able to find the origin of the segmentation fault.

I use 1 header and 1 cpp file. Update The Reason is that I want to Make multiple Command like print and instatiate different commands and call the Execute method without knowing what exactly command this is.

This is declared in one header File :

  class Command{
    public:
     virtual int Execute(std::stack<NumericData>* stack)=0;
  };

  class Print : public Command{
    public:
     int Execute(std::stack<NumericData>* stack);
  };

This is the implementation one cpp file:

 ... // inside some function
    std::stack<NumericData> stack;
    Command* command;
    if(1){                         // if is updated
        Print print;               // and reason for seg fault
        command=&print;            // without if it works
    }
    command->Execute(&stack); // <- segmentation fault
    ...

    int Command::Execute(std::stack<NumericData>* stack){
          printf("Execute parent\n");
          return 0; 
    }

    int Print::Execute(std::stack<NumericData>* stack){
          printf("Execute child\n");
          return 1;
    }
1 Answers

The problem is not related to your virtual functions, or to the override. It is simply that you are using the address of an object that no longer exists.

In the following code block:

    Command* command;
    if(1){                         // if is updated
        Print print;               // and reason for seg fault
        command=&print;            // without if it works
    }
    command->Execute(&stack); // <- segmentation fault

the lifetime of the print variable is restricted to its enclosing scope (the { ...}). Thus, the address you assign to command is no longer valid when you have left that scope, and your command->Execute(&stack); line is attempting to dereference a pointer to an object that no longer exists, causing the segmentation fault.

Related