-2

segmentation error happend. I check the code for long time then I find the clue. need to check the scope of local variable.

void main()
{
  parseoption po();
  {

   int a;
   po.register(&a)
  }
  some code maybe access to &a using po
}

in above case, when local variable a is deleted in stack? I think a only live in block { } but someone said local variable live in function, not block { }

when I remove the block of int a, no segmentation error happened. so I think int a only live in { }. Am I right??

user225549
  • 177
  • 2
  • 9
  • 3
    `main` has to return `int`, `register` is a keyword, you are missing a `;`, and other issues (eg `po` is a function due to most vexing parse) make this not valid code. A [mcve] could look like this: https://wandbox.org/permlink/gAxSC4cPGVFIrO4m . Please create a mcve before posting – 463035818_is_not_an_ai Aug 23 '19 at 08:41
  • 1
    Yes, local variables only live within the scope they are defined in and cannot legally be accessed from outside that scope. – Max Langhof Aug 23 '19 at 08:42
  • 1
    There are languages that work in the manner suggested to you by "someone", but C++ is not one of those languages. – molbdnilo Aug 23 '19 at 09:19

2 Answers2

1

Yes you are correct. a has automatic storage duration and its lifetime is limited to the scope blocks in which it occurs.

Both the pointer to a and what that pointer points to are invalid after a goes out of scope, and the behaviour on reading either is undefined.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
-1

The scope of your 'a' variable is defined within the two brackets. Before and after it, the variable does not exist.

You can use the address of 'a' with your 'register' method since they are in the same scope, but your 'some code maybe access to &a using po' crashes because outside of the scope. The address target nothing since the variable is destroyed.

If you want to fix your problem, you can use new to allocate dynamic memory for you variable. But in today's C++ new and delete are supposed to never appear. Maybe your logic is wrong and you should use a factory to create 'a' with the help of smart pointers.

Tiphaine
  • 193
  • 10