Why would this macro define goto, cause the program to crash?

I am reading a post, one of the answers has the following code

#define goto { int x = *(int *)0; } goto

      

There, the author claims that every time a person tries to use a goto statement, his program crashes, so my question is? In my opinion, int x = *(int *)0;

assigns any content in the first 4 bytes of the memory address x

, but why would that most likely crash the program?

+3


source to share


3 answers


Just because you are looking for a pointer NULL

. But then , that the program will fail is undefined. It might crash, it might not work, or it might do something strange. This is just undefined behavior and is best avoided.

It is worth noting that goto

it is not useless. Each keyword has a place, and there are reasons for authors and standard committee members to continue to support it (given that languages ​​make some significant changes). Used wisely, goto has a decent place in C and C ++.



Just to give an idea of ​​how this is UB using VC11, I have compiled the above snippet in debug and release mode. In debug mode it crashed, but in release mode the compiler just optimized the instruction and there was no crash there.

+7


source


In C or C ++, memory address 0 is a NULL pointer. The allocation of such a pointer is always undefined, and with a larger implementation it will cause segmentation faults, effectively crashing the program.



0


source


The code gives undefined behavior for two counters.

First, overriding a language keyword by itself gives undefined behavior.

Second, as others have said, a pointer with a value of "0" is a NULL pointer, and dereferencing it gives undefined behavior.

So the actual result of the construct is undefined. A common symptom of undefined behavior is a program crash. However, an accident is not really guaranteed. It isn't even required.

How why?" writing a macro, the author of this code, obviously, is a subscriber of the "goto is evil" camp and considers it necessary to arbitrarily impose his ignorant prejudices on others. Actually goto

has its uses, even though alternatives are often preferred. Even Dijkstra (the author of the original article that people often cite to justify the use goto

) only described the problems of rampant use and did not argue that it should simply be avoided. Donald Knuth later wrote an article on the topic in the mid 70s, including use cases goto

.

0


source







All Articles