简体   繁体   中英

How to return Segmentation fault in my custom class in C++?

I am building Stack Class using Linked List manually. I want to return Segmentation fault when the top() function is called on an empty Stack. How can I do that? Or some other error that I can return.

Segmentation faults are triggered by hardware and handled by the OS. You do not trigger them manually.

You can throw an exception: http://www.cplusplus.com/doc/tutorial/exceptions/ or you can decide on some value which indicates an error and return that.

If you have a pointer to the first element that is null or dangling (ie pointing to uninitialized/freed memory) when the list is empty, you can also dereference it as if there was a value. This will sometimes cause a segmentation fault and sometimes return bogus data. In this case it is up to the user not to call top on an empty list. Generally code does not guarantee to segfault in certain cases. Rather it sometimes happens when the hardware manages to catch a bad memory access.

If you post your code it will be easier to say how you can report the error in your concrete case.

How can I do that?

You could raise(SIGSEGV) . Alternatively abort() the execution.

You could also force read from invalid memory address, for example from the null pointer with like: *(volatile int*)0; .

Or some other error that I can return.

You should definitely not cause a segmentation fault condition intentionally in your program. Instead use an exception.

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